How can I correctly invoke a JavaScript function from a component in Angular 2 (TypeScript)?
Below is the code for my component:
import { ElementRef, AfterViewInit } from '@angular/core';
export class AppComponent implements AfterViewInit {
constructor(private _elementRef: ElementRef) {
}
ngAfterViewInit() {
/**
* Works but I get the following error:
* src/app.component.ts(68,9): error TS2304: Cannot find name 'MYTHEME'.
* src/app.component.ts(69,9): error TS2304: Cannot find name 'MYTHEME'.
*/
MYTHEME.documentOnLoad.init();
MYTHEME.documentOnReady.init();
/**
* Works without error, but doesn't seem like the correct approach
*/
var s = document.createElement("script");
s.text = "MYTHEME.documentOnLoad.init(); MYTHEME.documentOnReady.init();";
this._elementRef.nativeElement.appendChild(s);
}
}
Directly calling the JavaScript function results in 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 second way (appendChild) works without error, but it may not be the best way to go about it.
I came across this post about using a JavaScript function from TypeScript: Using a Javascript Function from Typescript. I tried declaring the interface:
interface MYTHEME {
documentOnLoad: Function;
documentOnReady: Function;
}
However, TypeScript doesn't seem to recognize it (no error in the interface declaration).
Thank you
Edit:
After following the advice from Juan Mendes, this is the updated code:
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();
}
}