How to access external javascript file from angular 2 component - javascript

I am very new to angular and front end web development, so maybe i am missing something
basic but i did not succeed to search a solution for that issue.
according to that answer: Call pure javascript function from Angular 2 component
and following that example
I am trying to import external .js file to my angular component:
import '../../../src/Plugin/codemirror/mode/custom/custom.js'
#Component({
selector: 'txt-zone',
templateUrl: 'app/txtzone/Txtzone.component.html',
styleUrls: ['app/txtzone/TxtZone.css'],
})
the path is the correct relative path, i know that because if it loads diractly from the url text box via the browser [http://localhost:50371/src/Plugin/codemirror/mode/custom/custom.js]
i can see the file content...
this is the exception that the chrome debugger is throwing:
zone.js:2263 GET
http://localhost:50371/src/Plugin/codemirror/lib/codemirror 404 (Not
Found)
as you can see the path was changed (don`t understand why?)
1. how can i solve this issue?
2. why the path of the .js file is not the referenced path?
3. maybe there is a better way to load external .js file into my component?
it looks quite trivial question but after hours of searching i could not find any answer.

A simple way to include custom javascript functions in your Angular 4 project is to include the item in your assets folder, and then use require to import it into your component typescript.
src/assets/example.js
export function test() {
console.log('test');
}
src/app/app.component.ts
(before #Component(...))
declare var require: any;
const example = require('../assets/example');
(inside export class AppComponent implements OnInit { ...)
ngOnInit() {
example.test();
}

Related

Angular 8 baseUrl gets wiped out

What we try to do is integrate and angular app in a PHP environment.
So the site will completely run on PHP for the static context, only when the user clicks on login, the will end up in the angular part.
So, now the problem.
When we enter the URL in PHP, it will be something like ...domain/nl/page.
So far so good, and this get redirected to angular, also this works, angular load.
But then angular deletes the last part of the link and changes it to
...domain/{pageThatAngularIsIn}.
This is where we want to keep the language en the URL should be
.../domain/nl/{pageThatAngularIsIn} or even
.../domain/nl/page/{pageThatAngularIsIn} -> step by step
So angular should ignore the language part in the URL but also not wipe it form the URL.
Anybody know if this is possible of why this happens?
Your problem is probably happening because Angular thinks that domain/ is the base route on which it should append its own routing. From your description, it sounds like you wan the base route to be domain/nl/ instead.
This is a simple fix. In the index.html file that has your angular root component embedded, look for a base element in the head and set it to the base path. By default, it's usually something like this:
<base href="/">
Experiment with it to get what you need. Perhaps:
<base href="/nl">
See the docs
If you will need to use that same base within your angular app, for instance to make http calls in a way that will use the same base, you should probably use the APP_BASE_HREF in your root module providers instead. Like:
import {Component, NgModule} from '#angular/core';
import {APP_BASE_HREF} from '#angular/common';
#NgModule({
...
providers: [{provide: APP_BASE_HREF, useValue: '/nl'}]
})
class AppModule {}
With this you will be able to inject the base in your services, for example to make your http calls.
#Injectable()
export class MyService {
constructor(
private http: HttpClient,
#Inject(APP_BASE_HREF) private baseHref: string
) {}
getRecords() {
return this.http.get(this.baseHref + '/records')
}
}
See the docs

Angular2, error when trying to add new module

I am trying to create a component called my-checklist, but I'm having issues running it.
I've declared the new module in app.ts as well as imported it, but it doesn't seem to be able to find my html file.
The error I get is:
zone.js:661 Unhandled Promise rejection: Failed to load checklist.component.html ; Zone: <root> ; Task: Promise.then ; Value: Failed to load checklist.component.html undefined
https://plnkr.co/edit/WZSc1X7whm658LEHidC4?p=preview
The problem is in your app.ts.
You try to open your component but you link to the app your module can't find your html cause you link it to your app.ts not to your component.ts.
In your app.ts you say
bootstrap: [ App ]
It should be
bootstrap: [ MyCheckList ]
Try and follow https://angular.io/tutorial if not get it there a demos you can checkout.
Had some time made a plunker: https://plnkr.co/edit/1v0cd9y8BZ0KTQUDlhik?p=preview also note that plunker need src/*.html for some reason. normal you use ./ for that.
When trying to load checklist.component.html the URL is relative to your index.html and that is why it is failing. Just change it to
#Component({
selector: 'my-checklist',
templateUrl: 'src/checklist.component.html'
})
This will make it work. But, I'll recommend that you find out a way to convert your templates in a variable and avoid the relative path issue. I don't know typescript, but I know Babel do it, maybe this would work.
import template from './checklist.component.html';
#Component({
template: template,
selector: 'my-checklist'
})
For example, if using Babel, after transpiled the import will look like this
var template = '<p>Test</p>';
Awesome, eh?
Check this other questions, probably will help
Is it possible to import an HTML file as a string with TypeScript?
How to import external HTML files into a TypeScript class

Angular 2 Execute JS from file using AfterViewInit

Quite new to Angular 2, and after looking around for few hours I'd like to have some help.
I have a JS file with some generic functions. For example:
$(document).ready(function(){
$('[data-toggle="tooltip"]').tooltip();
});
This file contains in fact way more code. As you can imagine, I'd like to enable tooltips of all components. I can't simply include this file in index.html because subcomponents aren't present (yet) when the file is loaded.
After some digging, afterViewInit() came up. This post suggests to copy/paste JS code into ngAfterViewInit(). That's the ugly way (in my opinion)...
So here I come with 2 related questions:
1# Is there a way to execute JS code when a child component is loaded? For example, something like:
// In app.component.ts
ngAfterChildComponentLoaded(){
// JS code here
}
This solution is quite interesting because I'm not forced to implement ngAfterViewInit() with the same content in all my components. But is it possible?
2# Is there a way to import JS code instrad of copy/paste it into ngAfterViewInit()? I don't want copy/paste 300 lines of JS code into 15 differents components (for obvious reasons).
Thanks a lot for your help!
See the following for how to get external js files for a particular component in angular 2/4:
import { Component, OnInit , AfterViewInit} from '#angular/core';
import { Router } from '#angular/router';
declare var $: any;
#Component({
moduleId: module.id,
selector: 'dashboard',
templateUrl: './dashboard.html',
styleUrls: ['./dashboard.css']
})
export class DashboardComponent implements OnInit,AfterViewInit {
constructor() {}
ngOnInit() {
}
ngAfterViewInit(){
$.getScript('assets/assets/build/js/custom.min.js');
}
}
Got a less-ugly solution, if someone has a better one I'll gladly accept his answer!
ngAfterViewInit(){
$.getScript('assets/js/myscript.js', function(){});
}

How to include external JavaScript libraries in Angular 2?

I am trying to include an external JS library in my Angular 2 app and trying to make all the methods in that JS file as a service in Angular 2 app.
For eg: lets say my JS file contains.
var hello = {
helloworld : function(){
console.log('helloworld');
},
gmorning : function(){
console.log('good morning');
}
}
So I am trying to use this JS file and reuse all the methods in this object and add it to a service, so that my service has public methods, which in turn calls this JS methods. I am trying to reuse the code, without reimplementing all the methods in my typescript based Angular 2 app. I am dependent on an external library, which I cant modify.
Please help, thank you in advance.
With ES6, you could export your variable:
export var hello = {
(...)
};
and import it like this into another module:
import {hello} from './hello-module';
assuming that the first module is located into the hello-module.js file and in the same folder than the second one. It's not necessary to have them in the same folder (you can do something like that: import {hello} from '../folder/hello-module';). What is important is that the folder is correctly handled by SystemJS (for example with the configuration in the packages block).
When using external libs which are loaded into the browser externally (e.g. by the index.html) you just need to say your services/component that it is defined via "declare" and then just use it. For example I recently used socket.io in my angular2 component:
import { Component, Input, Observable, AfterContentInit } from angular2/angular2';
import { Http } from 'angular2/http';
//needed to use socket.io! io is globally known by the browser!
declare var io:any;
#Component({
selector: 'my-weather-cmp',
template: `...`
})
export class WeatherComp implements AfterContentInit{
//the socket.io connection
public weather:any;
//the temperature stream as Observable
public temperature:Observable<number>;
//#Input() isn't set yet
constructor(public http: Http) {
const BASE_URL = 'ws://'+location.hostname+':'+location.port;
this.weather = io(BASE_URL+'/weather');
//log any messages from the message event of socket.io
this.weather.on('message', (data:any) =>{
console.log(data);
});
}
//#Input() is set now!
ngAfterContentInit():void {
//add Observable
this.temperature = Observable.fromEvent(this.weather, this.city);
}
}

Referencing in a simple way using AngularJS and TypeScript

I'm using VS2015 with Gulp and I'm trying to build AngularJS with TypeScript.
In my index.html, I have a script tag to my "app.js" (the output and bundle of the TS build).
However if I want to reference my controller, and any other services - how can I avoid having to put the relevant script tags in each and every HTML file - is there a way I can just reference the app.js file and be done with it? What's the recommended approach?
Cheers,
if you want to refrence only one file in html via script tag and other files just reference in other js files then you can use requirejs. It is a nice tool to load scripts. in production it is a good approach to concat and minify all your scripts to reduce number of requests.
I managed to resolve it using experimental typescript decorators, requirejs and a little of imagination.
So, in resume I wrote two decorators one called AppStartup and other called DependsOn. So at angular bootstrap I can get and register all dependencies.
I ended up with something like it:
TodoListController.ts
import {DependsOn, AppStartup, ngControllerBase} from "../infra/core";
import {taskManagerDirective} from "../directives/TaskManagerDirective";
#AppStartup({
Name: "TodoSample"
}).Controller({
DependsOn: [taskManagerDirective]
})
export class TodoListController extends ngControllerBase {
public ByControllerAs: string;
constructor() {
super(arguments);
let $httpPromise = this.$get<ng.IHttpService>("$http");
$httpPromise.then(function ($http) {
$http.get('http://www.google.com').success(function (body) {
console.info("google.com downloaded, source code: ", body);
});
});
this.ByControllerAs = "This was included by controllerAs 'this'";
}
}
rowListItemDirective.ts
import {DependsOn, ngDirectiveBase} from "../infra/core";
import {rowListItemDirective} from "./RowListItemDirective";
#DependsOn([rowListItemDirective])
export class taskManagerDirective extends ngDirectiveBase{
public template: string = `
Parent Directive
<table>
<tbody>
<tr row-list-item-directive></tr>
</tbody>
</table>
`;
}
You can see what I did below at my github repository:
https://github.com/klaygomes/angular-typescript-jasmine-seed

Categories

Resources