角度渲染动态附加<script> -tag在组件中

时间:2017-12-18 14:55:31

标签: javascript jquery angular

我试图在角度组件DOM中注入HTML模板。这些HTML模板包含&lt; div&gt; -tag和&lt; script&gt; -tag。

&#xA;&#xA;

模板。 html

&#xA;&#xA;
 &lt; div&gt;一些文字&lt; / div&gt;&#xA;&lt; script&gt;(function(){alert(“我在这里!” );}})()&lt; / script&gt;&#xA;  
&#xA;&#xA;

当我在 TestComponent中使用纯角度执行此操作时

&#XA;&#XA;

测试comp.component.ts

&#XA;&#XA;
 <代码> @Component({&#XA ; selector:“[test-comp]”,&#xA; templateUrl:“./ test-comp.component.html”,&#xA; styleUrls:[“./ test-comp.component.css”] &# xA;})&#xA;导出类TestComponent实现OnInit {&#xA; private _snippet:SafeHtml;&#xA;&#xA; get snippet():SafeHtml {return this._snippet; }&#XA;&#XA;构造函数(&#xA; private domSanitizer:DomSanitizer&#xA;){}&#xA;&#xA; ngOnInit(){&#xA; const模板:string = require(“module / dist / template.html”);&#xA; this._snippet = this.domSanitizer.bypassSecurityTrustHtml(template);&#xA; }&#xA;}&#xA;  
&#xA;&#xA;

组件HTML如下所示:

&#xA;&#xA;

test -comp.component.html

&#xA;&#xA;
 &lt; div id =“some_id”[innerHTML] =“snippets”&gt;&lt; / div&gt;&#xA;  
&#xA;&#xA;

这将在DOM中正确注入模板,但&lt; script&gt; -tag将不会实现我不会提醒任何事情。

&#xA;&#xA;

如果我使用jQuery将相同的模板注入同一个组件中,那么&lt; script&gt; -tag将是已实施,它将提醒文本。

&#xA;&#xA;

test-comp.component.ts

&#xA;&#xA;
  @Component ({&#xA; selector:“[test-comp]”,&#xA; templateUrl:“./ test-comp.component.html”,&#xA; styleUrls:[“./ test-comp.component。 css“]&#xA;})&#xA;导出类TestComponent实现OnInit {&#xA;构造函数(&#xA;){}&#xA;&#xA; ngOnInit(){&#xA; const模板:string = require(“module / dist / template.html”);&#xA; $( “#SOME_ID”)后(模板);&#XA; }&#xA;}&#xA;  
&#xA;&#xA;

这种现象有什么解释吗?我很想知道其中的差异!为什么jQuery有效?

&#xA;&#xA;

注意 :我的问题与问题,因为我会问:为什么用 jQuery <呈现它? / code>而不是使用 domSanitizer 进行渲染。我不问:怎么做?

&#xA;

1 个答案:

答案 0 :(得分:0)

Angular.io - HTML是Angular模板的语言。几乎所有HTML语法都是有效的模板语法。该元素是一个值得注意的例外;它是被禁止的,消除了脚本注入攻击的风险。在实践中,将被忽略并在浏览器控制台中显示警告。有关详细信息,请参阅Security页面。

但是,您可以使用以下方法绕过安全:DomSanitizer