我有一个脚本,希望只在一个组件上运行。我设法实现了在组件上添加脚本,但是发生了一些事情,但我不确定如何解决。
component.ts
import { Component, OnInit } from '@angular/core';
import { Renderer2, Inject } from '@angular/core';
import { DOCUMENT } from '@angular/platform-browser';
@Component({
selector: 'app-privacy',
templateUrl: './privacy.component.html',
styles: []
})
export class PrivacyComponent implements OnInit {
constructor(private _renderer2: Renderer2, @Inject(DOCUMENT) private _document) {
let s = this._renderer2.createElement('script');
s.type = `text/javascript`;
s.src = `../../assets/scripts/privacy.js`;
this._renderer2.appendChild(this._document.body, s);
}
ngOnInit() {
}
}
答案 0 :(得分:0)
您运行此js文件的方法是错误的,您应该执行以下操作以干净的方式实现此目的:
angular-cli.json
"scripts": [
"assets/js/privacy.js"
]
component.ts
import { Component, OnInit } from '@angular/core';
declare function myFunc(): any; // function from privacy.js
@Component({
selector: 'app-privacy',
templateUrl: './privacy.component.html',
styles: []
})
export class PrivacyComponent implements OnInit {
constructor() {
}
ngOnInit() {
myFunc(); // call it
}
}
答案 1 :(得分:0)
您需要在脚本元素中添加onload
(如果需要支持IE,请确保也支持onreadystatechange
)处理程序,该处理程序可以在脚本完成后调用您要执行的函数加载中。
要删除脚本onNgDestroy,请在组件上保存createElement?
的引用,并在“销毁”生命周期挂钩中将其删除。
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Renderer2, Inject } from '@angular/core';
import { DOCUMENT } from '@angular/platform-browser';
@Component({
selector: 'app-privacy',
templateUrl: './privacy.component.html',
styles: []
})
export class PrivacyComponent implements OnInit, OnDestroy {
private s: any;
constructor(private _renderer2: Renderer2, @Inject(DOCUMENT) private _document) {
this.s = this._renderer2.createElement('script');
this.s.type = `text/javascript`;
this.s.src = `../../assets/scripts/privacy.js`;
this.s.onload = this.doneLoading;
this._renderer2.appendChild(this._document.body, this.s);
}
doneLoading () {
// do what you need to do
}
ngOnDestroy() {
// this removes the script so it won't be added again when the component gets initialized again.
this._renderer2.removeChild(this._document.body, this.s)
}
ngOnInit() {
}
}