2017-12-02 12 views
0

基本上我想有一個textarea,用戶可以粘貼HTML(的電子郵件),和預覽應當顯示一個用戶。我試圖通過採取HTML並將它傳遞給一個組件實現此渲染字符串作爲HTML,這樣的事情:當通過與<style>標籤定義爲[innerHTML的]風格的HTML,防止他們影響整個應用

<div [innerHTML]="html"></div> 

這樣做的問題是,如果用戶寫了這樣的事情:

<html> 
    <head> 
     <style> 
      h1 {color:red;} 
     </style> 
    </head> 
    <body> 
     <h1>Test</h1> 
    </body> 
</html> 

組件將正確呈現此html,但樣式會影響整個應用程序。

enter image description here

enter image description here

我怎樣才能使它所以用戶添加僅影響底部的組件樣式,這使得該HTML?

我知道關於組件的範圍,但這不完全是因爲我不是定義這些樣式的樣式。

+0

我不知道如果我理解的很好,你是否試圖讓組件的視圖動態化? – Luillyfe

+0

是的,我想你可以這麼說。我希望用戶能夠粘貼電子郵件模板,但爲了確保它是正確的,它應該呈現爲html格式。這很好,實際上這不是問題。問題是添加的任何樣式都會影響整個應用程序。我只希望他們影響電子郵件模板。 – Christian

回答

0

有關嵌套組件的更多信息,請參閱Angular documentation。 你得到了你的整個HTML替換,因爲深入你這樣做。請讓我澄清一下。您需要構建一個可嵌套組件來與之交談,並傳遞其html視圖。

app.component.ts(容器組件)

import { Component } from '@angular/core'; 

@Component({ 
    selector: 'app', 
    templateUrl: './app.component.html', 
    styleUrls: ['./app.component.css'] 
}) 
export class AppComponent { 
    /* Bound property to get the html from your texarea element */ 
    html: any; 
    pageTitle: string = 'I am a container'; 
} 

app.component.html

<!-- this styles classes are from bootstrap --> 
<div class="panel panel-primary"> 
    <div class="panel-heading" > 
    {{ pageTitle }} 
    </div> 
    <div class="panel-body"> 
    <div class="row"> 
     <div class="col-md-2"></div> 
     <div class="col-md-4"> 
     <div class="form-group"> 
      <label for="exampleFormControlTextarea1">Add Html:</label> 
      <textarea class="form-control" id="exampleFormControlTextarea1" rows="3" [(ngModel)]='html' ></textarea> 
     </div> 
     </div> 
    </div> 
    <app-child [htmlPreview]='html'></app-child> 
    </div> 
</div> 

這是爲您的孩子組件的代碼: appChild。 component.ts

import {Component} from '@angular/core'; 

@Component({ 
    selector: 'app-child', 
    templateUrl: './appChild.component.html' 
}) 
export class AppChildComponent { 
    /* This is an Input property that tells Angular where to place the html from your textArea element */ 
    @Input() htmlPreview; 

} 

最後你appChild.component.html

<div class="panel panel-primary" [innerHtml]='htmlPreview'> 
    <div class="panel-heading"></div> 
</div> 

/*其實這並不重要,你把這裏的,因爲它的操作系統將被替換爲您的文本區域的HTML。 但什麼是真正重要的是[的innerHTML =「htmlPreview」是領帶到您的輸入特性 */

不要忘記添加AppChild組件模塊上:

... 

import { AppComponent } from './app.component'; 
import { AppChildComponent } from './appChild.component'; 

@NgModule({ 
    declarations: [ 
    AppComponent, 
    AppChildComponent 
    ], 
    ... 
}) 
export class AppModule { } 
+0

是的,這幾乎是我所做的,這不是問題。問題是,如果用戶在該textarea中寫入任何樣式,那麼這些樣式會影響整個App。我希望它僅影響innerHTML – Christian