I have a legacy script that I need to include in my angular application.
The thing about this script is that it relates to a specific component, and it has to be loaded only after the view of the component is loaded.
As for today, I succeeded to include it on OnInit function but sometimes (not always for some reason) the CLI throws an error about it.
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-player-page',
templateUrl: './player-page.component.html',
styleUrls: ['./player-page.component.scss']
})
export class PlayerPageComponent implements OnInit {
public itemId: string;
constructor() {}
ngOnInit() {
//We loading the player srcript on after view is loaded
require('assets/scripts/player/player.js');
}
}
The script assumes that elements in the UI exists and it searches them by the id.
When adding it on top of the page, it doesn’t work.
What is the best way to achieve the desired behavior?
There are multiple solutions to this issue.
-
declare the
require
const on top of your componentdeclare const require: any; import { Component, OnInit } from '@angular/core'; @Component({}) ...
-
use the dynamic
import()
function from typescriptngAfterViewInit() { //We loading the player script on after view is loaded import('assets/scripts/player/player.js'); }
-
change the library to only start running after you call a function from the component, this way you can add it to the scripts array of your
angular.json