我已经做了一些阅读和搜索,几乎我发现的一切都指出脚本标签不能包含在Angular 2的模板中.
我们正在故意从模板中删除标签,因为您不应该使用它们按需加载代码. https://github.com/angular/angular/issues/4903 [2015]
但是 - 有一个功能bypassSecurityTrustScript
我想知道bypassSecurityTrustScriptAngular 2的使用时间和方式是什么意思?
我知道有一个类似的问题被问到:
Angular2动态插入脚本标签 - 虽然没有人回答他们如何使用的问题bypassSecurityTrustScript,但我不确定提供的问题的答案是如何工作的,因为它似乎在一个内部使用JavaScript模板.
Mar*_*ong 27
在视图中使用脚本通常是一种不好的做法.如果你坚持这样做,你可以使用这个组件:
scripthack.component.html:
<div #script style.display="none">
<ng-content></ng-content>
</div>
Run Code Online (Sandbox Code Playgroud)
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();
}
}
Run Code Online (Sandbox Code Playgroud)
用法(内联):
<script-hack>alert('hoi');</script-hack>
Run Code Online (Sandbox Code Playgroud)
用法(外部):
<script-hack src="//platform.twitter.com/widgets.js" type="text/javascript"></script-hack>
Run Code Online (Sandbox Code Playgroud)
结果我觉得这有点不对劲.我试图通过使用标准的Angular模板变量找到一种将脚本放入模板的方法.当Angular填充模板时,它会清除值,因此脚本标记会丢失.
我设法在以下文章中获得脚本标记:https: //netbasal.com/angular-2-security-the-domsanitizer-service-2202c83bd90#.7njysc6z1
然后,我将问题描述为:Angular2动态插入脚本标记
然后我基于此将逻辑移动到组件类中: DOM操作在Angular 2中属于哪里?
| 归档时间: |
|
| 查看次数: |
44383 次 |
| 最近记录: |