【发布时间】:2018-07-05 22:41:21
【问题描述】:
如何防止使用innerHtml 添加到子组件的子组件样式应用于父组件?巧合的是,父级可能已经有一个同名的 css 类。如果 ViewEncapsulation 设置为 Native,这似乎可以正常工作(孩子有红色背景,父母有绿色),但使用 Emulated 它不会。我不能用Native,据说不是所有浏览器都支持。
app.ts
import {Component, NgModule, VERSION} from '@angular/core'
import {BrowserModule, DomSanitizer} from '@angular/platform-browser'
import {Component, Input, ViewEncapsulation} from '@angular/core'
@Component({
selector: 'my-app',
template: `<div class="header">
<h2>Hello {{name}}</h2>
</div>
<hr>
<child [content]="content"></child>
`,
})
export class App {
name:string;
content:string = '<style>.header {background-color:red;color:white;}</style><div class="header">This is child content</div>'
constructor(public ds: DomSanitizer) {
this.content = this.ds.bypassSecurityTrustHtml(this.content);
this.name = `Angular! v${VERSION.full}`
}
}
@Component({
selector: 'child',
template:`<div [innerHtml]="content"></div>`,
encapsulation:ViewEncapsulation.Emulated
// encapsulation:ViewEncapsulation.Native
})
export class child{
@Input('content') content;
}
@NgModule({
imports: [ BrowserModule ],
declarations: [ App, child ],
bootstrap: [ App ]
})
export class AppModule {}
style.css
.header {
background-color:green;
color:white;
}
【问题讨论】:
-
原生模式在 Firefox 中不起作用,但在 Chrome 中起作用