I have one file that have dozens javascript functions. What I want to do is to import that file into Angular 2 component and run init() function that is defined in "external.js" file.
import { Component, AfterViewInit } from '#angular/core';
import "../../../../assets/external.js";
#Component({
selector: 'app-component',
templateUrl: 'app.component.html'
})
export class ComponentNameComponent implements AfterViewInit {
constructor() { }
ngAfterViewInit(): void {
// invoke init() function from external.js file
}
}
external.js is loaded using import and in ngAfterViewInit() I want to invoke init() function that is in external.js that calls all other methods in that external file.
Here is part of external.js:
function init() {
callFunction1();
callFunction2();
}
You can import and declare your external object. after then you can use it in your component.
import 'external.js'
declare var myExtObject: any;
I made an example in plunker:
https://plnkr.co/edit/4CrShwpZrDxt1f1M1Bv8?p=preview
Hope this helps.
Checkout my git project of angular 6 - I used this in login component -
https://github.com/gajender1995/Angular-HighChart-Auth
exter.js
define(["require", "exports"], function(require, exports){
exports.value = "aaa";
exports.gajender = function(){console.log(2)};
});
login.component.ts
import * as MyModule from './exter.js';
console.log('my value is', MyModule.gajender());
In tsconfig Add
"allowJs": true
Related
I have a script that I would like to run on one component only. I have managed to achieve adding the script on the component but a couple of things happen that I'm not entirely sure how to resolve.
If I navigate to the component, the script is added to the DOM, but it isn't firing. If I refresh the page, it works
If I navigate away to another component and return, the script is added again, and it can keep building up
component.ts
import { Component, OnInit } from '#angular/core';
import { Renderer2, Inject } from '#angular/core';
import { DOCUMENT } from '#angular/platform-browser';
#Component({
selector: 'app-privacy',
templateUrl: './privacy.component.html',
styles: []
})
export class PrivacyComponent implements OnInit {
constructor(private _renderer2: Renderer2, #Inject(DOCUMENT) private _document) {
let s = this._renderer2.createElement('script');
s.type = `text/javascript`;
s.src = `../../assets/scripts/privacy.js`;
this._renderer2.appendChild(this._document.body, s);
}
ngOnInit() {
}
}
You need to add the onload (if you need to support IE make sure to also support onreadystatechange) handler to your script element which can call a function you want to execute when the script is finished loading.
To remove the script onNgDestroy, save a reference of createElement? on the Component and remove this in Destroy lifecycle hook.
import { Component, OnInit, OnDestroy } from '#angular/core';
import { Renderer2, Inject } from '#angular/core';
import { DOCUMENT } from '#angular/platform-browser';
#Component({
selector: 'app-privacy',
templateUrl: './privacy.component.html',
styles: []
})
export class PrivacyComponent implements OnInit, OnDestroy {
private s: any;
constructor(private _renderer2: Renderer2, #Inject(DOCUMENT) private _document) {
this.s = this._renderer2.createElement('script');
this.s.type = `text/javascript`;
this.s.src = `../../assets/scripts/privacy.js`;
this.s.onload = this.doneLoading;
this._renderer2.appendChild(this._document.body, this.s);
}
doneLoading () {
// do what you need to do
}
ngOnDestroy() {
// this removes the script so it won't be added again when the component gets initialized again.
this._renderer2.removeChild(this._document.body, this.s)
}
ngOnInit() {
}
}
Your approach in running this js file is wrong, you should do following to achieve this in the clean way:
Add your js file to the assets (for example assets/js/privacy.js)
Add file to the .angular-cli.json scripts
Now you can call your js functions from angular components if you declare them in the component
angular-cli.json
"scripts": [
"assets/js/privacy.js"
]
component.ts
import { Component, OnInit } from '#angular/core';
declare function myFunc(): any; // function from privacy.js
#Component({
selector: 'app-privacy',
templateUrl: './privacy.component.html',
styles: []
})
export class PrivacyComponent implements OnInit {
constructor() {
}
ngOnInit() {
myFunc(); // call it
}
}
I want to import js file in typescript.
And I want to access object and function in the js files.
Also I added js file in index.html but It doesn't working too.
so I find a clue that "import '[js file path]'" but it doesn't working.
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import { NavParams } from 'ionic-angular';
import '../../pages/mobile.js';
#Component({
selector: 'page-success',
templateUrl: 'success.html'
})
export class SuccessPage {
constructor(public navCtrl: NavController, public navParms: NavParams) {
let centerPos = new atlan.maps.UTMK(953933.75, 1952050.75);
}
}
This is success.ts file. I want to find 'atlan' object.
Give me a solution please. Thx a lot!
You have to use the declare keyword so you do not get any compilation errors. You can do the following
import { Component } from '#angular/core';
....
/* Here you are telling typescript compiler to
ignore this variable it did not originate with typescript.*/
declare var atlan: any;
#Component({
selector: 'page-success',
templateUrl: 'success.html'
})
export class SuccessPage {
....
}
In your file ../../pages/mobile.js, you must export your atlan object (if you can edit this file of course), then, you import it the same way you do with everything.
In my normal HTML page I am having a simple 4 line code shown below:
<script>
var getData = JSON.parse(localStorage.getItem("templateType"));
document.write(getData.template_code); // in angular its wriiten as getData["template_code"]
console.log(getData.template_code);
document.getElementById("main-wrapper").innerHTML = getData.template_code;
</script>
How can I do the same in Angular 2, I have a component webview.component.html and webview.component.ts?
You can import document object inside your angular component in this way:
import { Inject, Injectable } from '#angular/core';
import { DOCUMENT } from '#angular/platform-browser';
So you use it:
#Injectable()
export class MyService {
constructor(#Inject(DOCUMENT) private document: any) {
document.write(getData.template_code);
}
}
There is a pretty similar question here.
I have a function like this
myHelperNumber.js
function myLittleBoy(){
console.log('I see you)
}
How to use this function in User.js component or userSevicer.js service?
myHelperFunction.ts
export function myLittleBoy(){
console.log('Hello World')
}
RegisterComponent.ts
import {myLittleBoy} from 'path to myhelperfunction.ts'
export function myLittleBoy(){
console.log('I see you)
}
import { Component } from '#angular/core';
declare var myLittleBoy:any;
#Component({
selector: 'my-app',
template: '<h1>Hello {{name}}</h1>',
})
export class AppComponent {
constructor(private __jsmodel:JSmodelEvents){
myLittleBoy();
}
}
import {myHelperNumber} from 'your path';
export class AppComponent{
constructor(private helpNum: myHelperNumber){
// Now you can use myLittleBoy function anywhere inside the AppComponent Class
// Like below shown:
// this.helpNum.myLittleBoy();
}
}
Make sure your myHelperNumber file is in exportable format.
myHelperNumber.ts:
export const function myLittleBoy(){
console.log('I see you)
}
Then in User.ts or userService.ts
import {myLittleBoy} from './myHelperNumber';
// and just use it in this class
I have an Angular 2 application. For mocking the Document object in tests, I'd like to inject it to the service like:
import { Document } from '??'
#Injectable()
export class MyService {
constructor(document: Document) {}
}
The Title service of Angular uses the internal getDOM() method.
Is there any simple way to inject the Document to the service? Also, how should I reference it in the providers array?
This has been supported by Angular for a while.
You can use the DOCUMENT constant provided by the #angular/common package.
Description of the DOCUMENT constant (taken from the API documentation):
A DI Token representing the main rendering context. In a browser, this is the DOM Document.
An example is as shown below:
my-service.service.ts:
import { Inject, Injectable } from '#angular/core';
import { DOCUMENT } from '#angular/common';
#Injectable()
export class MyService {
constructor(#Inject(DOCUMENT) private document: Document) {}
}
my-service.service.spec.ts
import { provide } from '#angular/core';
import { DOCUMENT } from '#angular/common';
import { MyService } from './my-service';
class MockDocument {}
describe('MyService', () => {
beforeEachProviders(() => ([
provide(DOCUMENT, { useClass: MockDocument }),
MyService
]));
...
});
I'm unable to comment directly on adamdport's question (not yet 50 rep points), but here it is as stated in the angular docs.
Blockquote
#GünterZöchbauer it looks like DOCUMENT is deprecated. Any idea how to do this once it's gone? For example, how would I set the favicon dynamically?
Instead of importing from platform browser like so:
import { DOCUMENT } from '#angular/platform-browser';
Import it from angular common:
import {DOCUMENT} from '#angular/common';
in addition to #Günter Zöchbauer's answer.
Angular define DOCUMENT as an InjectionToken
export const DOCUMENT = new InjectionToken<Document>('DocumentToken');
dom_tokens.ts
And inject it with document in browser.ts
{provide: DOCUMENT, useFactory: _document, deps: []}
export function _document(): any {
return document;
}
Therefore, when we use it, we just need to inject #Inject(DOCUMENT)
or use the token directly in deps:[DOCUMENT]
import { Inject, Injectable } from '#angular/core';
import { DOCUMENT } from '#angular/common';
#Injectable()
export class MyService {
constructor(#Inject(DOCUMENT) private document) {}
}
It's the ": Document" that's causing the problem.