需要在角度2中插入脚本标签 [英] Need to insert Script tag in angular 2
问题描述
我已经做了一些阅读和搜索,并且发现的几乎所有内容都表明Angular 2的模板中不能包含脚本标签.
I've already done a bit of reading and searching and pretty much everything I find points to that a script tag cannot be included in a template in Angular 2.
我们正在为您故意从模板中删除标签 不应使用它们按需加载代码. https://github.com/angular/angular/issues/4903 [2015]
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]
However - there is a function bypassSecurityTrustScript
我想知道何时以及如何使用Angular 2中的bypassSecurityTrustScript
?
I'd like to know when and how bypassSecurityTrustScript
in Angular 2 is intended to be used?
我知道有人问过类似的问题:
Angular2动态插入脚本标签-尽管没有人回答他们有关如何使用
I know a similar question has been asked:
Angular2 dynamically insert script tag - though no one answered their question of how to use bypassSecurityTrustScript
, and I'm not sure how the provided answer to that question could even work as it appears to use JavaScript within a template.
推荐答案
在视图中包含脚本通常是一种不好的做法.如果您坚持要执行此操作,则可以使用以下组件:
Having scripts in your views is usually a bad practice. If you insist on doing this you can use this component:
scripthack.component.html:
scripthack.component.html:
<div #script style.display="none">
<ng-content></ng-content>
</div>
scripthack.component.ts:
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>
这篇关于需要在角度2中插入脚本标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!