简体   繁体   English

Angular 5-加载视图后加载脚本

[英]Angular 5 - Loading Script After View Is Loaded

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. 对于今天,我已经成功地将其包含在OnInit函数中,但是CLI有时(并非总是出于某种原因)会引发错误。

 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. 该脚本假定UI中存在元素,并按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. 有多种解决方案。

  1. declare the require const on top of your component 在组件顶部声明require const

     declare const require: any; import { Component, OnInit } from '@angular/core'; @Component({}) ... 
  2. use the dynamic import() function from typescript 使用打字稿中的动态import()函数

     ngAfterViewInit() { //We loading the player script on after view is loaded import('assets/scripts/player/player.js'); } 
  3. 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 将库更改为仅在从组件调用函数后才开始运行,这样就可以将其添加到angular.json的scripts数组中

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM