Is there a proper way to call a JavaScript function from a component in Angular 2 (TypeScript)?
Here is my component:
import { ElementRef, AfterViewInit } from '@angular/core'; export class AppComponent implements AfterViewInit { constructor(private _elementRef: ElementRef) { } ngAfterViewInit() { MYTHEME.documentOnLoad.init(); MYTHEME.documentOnReady.init(); var s = document.createElement("script"); s.text = "MYTHEME.documentOnLoad.init(); MYTHEME.documentOnReady.init();"; this._elementRef.nativeElement.appendChild(s); } }
Calling the JavaScript function directly leads to a compilation error, but the syntax in the "compiled" JavaScript file (app.component.js) is correct:
AppComponent.prototype.ngAfterViewInit = function () { MYTHEME.documentOnLoad.init(); MYTHEME.documentOnReady.init(); };
The 2nd method (appendChild) works without errors, but I donβt think (changing the DOM from typescript / angular) is the right way to do this.
I found this: Using the Javascript function from Typescript I tried to declare an interface:
interface MYTHEME { documentOnLoad: Function; documentOnReady: Function; }
But TypeScript does not seem to recognize it (there is no error in the declaration of the interface).
thanks
Edit:
Following the answer of Juan Mendes, this is what I ended up with:
import { AfterViewInit } from '@angular/core'; interface MYTHEME { documentOnLoad: INIT; documentOnReady: INIT; } interface INIT { init: Function; } declare var MYTHEME: MYTHEME; export class AppComponent implements AfterViewInit { constructor() { } ngAfterViewInit() { MYTHEME.documentOnLoad.init(); MYTHEME.documentOnReady.init(); } }
javascript angular typescript
Joshua
source share