2016-10-19 26 views
2

我有一個端點,它返回自定義的html和腳本字符串。我需要告訴angular2這是一個安全的HTML,並將其呈現爲組件模板。到目前爲止我的代碼:在angular2組件中注入自定義腳本

import { Component } from '@angular/core'; 
import { DomSanitizer } from '@angular/platform-browser'; 

@Component({ 
    selector: 'my-app', 
    templateUrl: './app.template.html', 
}) 
export class AppComponent { 

    public htmlToRender: any; 

    constructor(
     private _sanitizer: DomSanitizer, 
    ) {} 

    public ngOnInit(): void { 

     const html = ` 
      <p>Hello</p> 
      <p id="a"></p> 
      <script> 
       document.getElementById("a").innerHTML = "World" 
       console.log(111); 
      </script> 
     `; 

     this.htmlToRender = this._sanitizer.bypassSecurityTrustHtml(html); 
    } 

} 

在我的模板,我有:

'<div [innerHTML]="htmlToRender"></div>' 

然而,這是行不通的。 Html和腳本標記被渲染成模板,但腳本不被執行。

回答

0

angular2將編譯並將模板呈現爲父級html。但它會運行任何腳本。所以你不能在服務器的html中添加任何<script>。可能你可以用ngAfterViewInit組件嘗試。例如,在ngAfterViewInit()函數中,加載腳本並使用js函數eval()進行評估。

+0

這對我而言不起作用,因爲帶有