Angular 5-加载视图后加载脚本 [英] Angular 5 - Loading Script After View Is Loaded

查看:33
本文介绍了Angular 5-加载视图后加载脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个旧脚本,需要将其包含在我的角度应用程序中.关于此脚本的事情是,它与特定的组件有关,并且仅在加载组件的视图之后才必须加载它.就今天而言,我已成功将其包含在OnInit函数中,但有时(并非总是出于某种原因)CLI会对此抛出错误.

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');
  }

}

该脚本假定UI中的元素存在,并且按ID搜索它们.将其添加到页面顶部时,它将不起作用.实现所需行为的最佳方法是什么?

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.

  1. 在组件顶部声明 require 常量

declare const require: any;

import { Component, OnInit } from '@angular/core';

@Component({})
...

  • 使用打字稿中的动态 import()函数

    ngAfterViewInit() {
      //We loading the player script on after view is loaded
      import('assets/scripts/player/player.js');
    }
    

  • 将库更改为仅在从组件调用函数后才开始运行,这样就可以将其添加到 angular.json

    这篇关于Angular 5-加载视图后加载脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆