我从HTTP调用中获得了大量的HTML代码。我把HTML块放在一个变量,并将它插入到我的页面[innerHTML],但我不能样式插入的HTML块。有人有什么建议吗?

@Component({
  selector: 'calendar',
  template: '<div [innerHTML]="calendar"></div>',
  providers: [HomeService], 
  styles: [`h3 { color: red; }`]
})

我想要样式的HTML是包含在变量“日历”中的块。


当前回答

我们经常从我们的CMS中提取内容作为[innerHTML]="content.title"。我们将必要的类放在应用程序的根样式中。SCSS文件而不是组件的SCSS文件。我们的CMS特意剥离了内联样式,所以我们必须准备好作者可以在其内容中使用的类。记住使用{{content。模板中的Title}}不会从内容中呈现HTML。

其他回答

我最初执行this.sanitizer.bypassSecurityTrustHtml()路由,并将封装设置为ViewEncapsulation。没有,但有两个问题:

ViewEncapsulation。NONE在我的组件中引起了其他样式问题 我的“安全”html似乎不工作与css变量,即var(——蓝色)

这对我来说是有效的(不需要更改任何其他内容):InsertAdjacentHTML

模板:

<div id=template></div>

代码:

ngOnInit() {
  const el = document.getElementById('template');
  el.insertAdjacentHTML('afterbegin', `<span style="color: var(--blue)">hello</span>`);
}

免责声明:在我的例子中,我是从配置文件中解析html。对于用户输入的html,您不会希望走这条路线。

如果你使用sass作为样式预处理器,你可以通过以下方式切换回原生sass编译器:

NPM安装node-sass

这样你就可以继续用/深/来发展。

使用下面的方法在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

你需要遵循的简单解决方案是

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

constructor(private sanitizer: DomSanitizer){}

transformYourHtml(htmlTextWithStyle) {
    return this.sanitizer.bypassSecurityTrustHtml(htmlTextWithStyle);
}

我们经常从我们的CMS中提取内容作为[innerHTML]="content.title"。我们将必要的类放在应用程序的根样式中。SCSS文件而不是组件的SCSS文件。我们的CMS特意剥离了内联样式,所以我们必须准备好作者可以在其内容中使用的类。记住使用{{content。模板中的Title}}不会从内容中呈现HTML。