2017-09-15 97 views
-1

你好我想從api返回的文件中添加html,這是工作。我需要幫助的是當我添加一個內聯樣式它不起作用,但如果我創建一個類在style.css它並將其添加到HTML它然後工作。Angular 2將HTML動態添加到DOM,風格不起作用

所有這一切說,我需要獲得內聯風格的工作。我想獲得<span style="color:red;">I am red</span>的工作。

@Component({ 
    selector: 'my-app', 
    template: ` 
    <div> 
     <h2>Hello {{name}}</h2> 
     <button (click)="onClick()">Click To Add Html</button> 
    </div> 
    <div *ngIf="html!==''" [innerHtml]="html"></div> 
    `, 
}) 
export class App { 
    name:string; 
    html:string=null; 

    const htmlConst:string = `<span style="color:red;">I am red</span>`; 
    /* 
    I have tried [style] = "color:red;" 
    style="color:red;" 
    */ 
    constructor() { 
    this.name = `Angular! v${VERSION.full}` 
    } 

    onClick():void{ 
    if(this.html !== ''){ 
     this.html= this.htmlConst; 
    } 
    else{ 
     this.html = ''; 
    } 
    } 
} 

任何意見將是有益的。

回答

1
import { Component,ViewEncapsulation } from '@angular/core'; 

    @Component({ 
     selector: 'my-app', 
     template: ` 
     <div> 
      <h2>Hello {{name}}</h2> 
      <button (click)="onClick()">Click To Add Html</button> 
     </div> 
     <div *ngIf="html!==''" [innerHtml]="html"></div> 
     `, 
    encapsulation: ViewEncapsulation.None 
    }) 

請從https://toddmotto.com/emulated-native-shadow-dom-angular-2-view-encapsulation

+0

是指你可以添加一個解釋,它是如何在這裏解決問題,而不是隻是一個參考鏈接? –

+0

參考鏈接有詳細的解釋。這個問題已經在堆棧溢出回答https://stackoverflow.com/questions/44210786/style-not-working-for-innerhtml-in-angular-2-typescript – Sundhar

+0

然後你應該標記爲重複 –