gpt4 book ai didi

angular - 需要在 Angular 2 中插入脚本标签

转载 作者:太空狗 更新时间:2023-10-29 16:55:06 30 4
gpt4 key购买 nike

我已经做了一些阅读和搜索,几乎所有我发现的东西都表明脚本标签不能包含在 Angular 2 的模板中。

we are removing tags from templates on purpose as you shouldn't use those to load code on demand. https://github.com/angular/angular/issues/4903 [2015]

但是 - 有一个函数bypassSecurityTrustScript

我想知道何时以及如何使用 Angular 2 中的 bypassSecurityTrustScript

我知道有人问过类似的问题: Angular2 dynamically insert script tag - 尽管没有人回答他们关于如何使用 bypassSecurityTrustScript 的问题,而且我不确定为该问题提供的答案如何工作,因为它似乎在模板中使用 JavaScript。

最佳答案

在您的 View 中使用脚本通常是一种不好的做法。如果你坚持这样做,你可以使用这个组件:

scripthack.component.html:

<div #script style.display="none">
<ng-content></ng-content>
</div>

scripthack.component.ts:

import { Component, ElementRef, ViewChild, Input } from '@angular/core';

@Component({
selector: 'script-hack',
templateUrl: './scripthack.component.html'
})
export class ScriptHackComponent {

@Input()
src: string;

@Input()
type: string;

@ViewChild('script') script: ElementRef;

convertToScript() {
var element = this.script.nativeElement;
var script = document.createElement("script");
script.type = this.type ? this.type : "text/javascript";
if (this.src) {
script.src = this.src;
}
if (element.innerHTML) {
script.innerHTML = element.innerHTML;
}
var parent = element.parentElement;
parent.parentElement.replaceChild(script, parent);
}

ngAfterViewInit() {
this.convertToScript();
}
}

用法(内联):

<script-hack>alert('hoi');</script-hack>

用法(外部):

<script-hack src="//platform.twitter.com/widgets.js" type="text/javascript"></script-hack>

关于angular - 需要在 Angular 2 中插入脚本标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42458346/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com