我从HTTP调用中获得了大量的HTML代码。我把HTML块放在一个变量,并将它插入到我的页面[innerHTML],但我不能样式插入的HTML块。有人有什么建议吗?
@Component({
selector: 'calendar',
template: '<div [innerHTML]="calendar"></div>',
providers: [HomeService],
styles: [`h3 { color: red; }`]
})
我想要样式的HTML是包含在变量“日历”中的块。
使用下面的方法在innerhtml中允许CSS样式。
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
.
.
.
.
html: SafeHtml;
constructor(protected _sanitizer: DomSanitizer) {
this.html = this._sanitizer.bypassSecurityTrustHtml(`
<html>
<head></head>
<body>
<div style="display:flex; color: blue;">
<div>
<h1>Hello World..!!!!!</h1>
</div>
</div>
</body>
</html>`);
}
示例代码stackblitz
或者使用下面的方法直接在HTML中编写。
https://gist.github.com/klihelp/4dcac910124409fa7bd20f230818c8d1
最简单、最直接的方法是使用angular project src文件夹中的全局样式文件。
假设组件选择器是:app-my-component
在app-my-component模板中,向innerHtml内容所在的元素中添加一个类:
<div class="innerhtml-class" [innerHTML]="variable.innerHtml"></div>
添加到全局样式文件:
app-my-component {
.innerhtml-class {
declaration goes here
}
}