ViewEncapsulation.None 无法使用 innerHTML

ViewEncapsulation.None not working with innertHTML


我实际上正在开发一个 angular 应用程序,我必须将一个 [innerHTML] 元素放在 div.

我的代码
像这样:
something.component.html

<section class="mx-auto" *ngFor="let publication of publication">
  <div [innerHTML]="publication.content"></div>
</section>

所以在 ts 中:
something.component.ts

import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import { Subscription } from 'rxjs';
import { ActivatedRoute } from '@angular/router';
import { Title, Meta } from '@angular/platform-browser';

import { Publication } from '../publication.model';
import { PublicationsService } from '../publication.service';

@Component({
  selector: 'app-free-publication',
  templateUrl: './something.component.html',
  styleUrls: ['./something.component.scss'],
  encapsulation: ViewEncapsulation.None
})

export class FreePublicationComponent implements OnInit {
  publication: Publication[] = [];
  suggestions: Publication[] = [];
  private routeSub: Subscription;
  getId: any;
  isLoading = false;

  constructor(public publicationsService: PublicationsService, private route: ActivatedRoute, private titleService: Title, private meta: Meta) {
    this.getId = this.route.url['_value'][1].path;
    this.getId = + this.getId;
  }

  ngOnInit() {
    this.isLoading = true;
    // main publication
    this.routeSub = this.route.params.subscribe(params => {
      this.publicationsService.getPublication(params['publicationId']).then(dataPublication => {
        for (let i = 0; (dataPublication.content.match(/wp-content/g) || []).length; i++) {
          dataPublication.content = dataPublication.content.replace('https://aurelienbamde.com/wp-content/', 'assets/content/');
        }
        this.titleService.setTitle(dataPublication.title);
        this.meta.addTag({ name: 'keywords', content: dataPublication.post_tag });
        this.publication = [dataPublication];
      });
    });
  }
}

而且我的 innertHTML 没有 return 我发送的 html 文档的样式。

我的测试
在 ngOnInit 的末尾使用 console.log(),我可以看到我的 html 具有所有样式属性,但是通过检查 innerHTML 的 div,里面没有样式。

我的问题
所以我很好地实现了 ViewEncapsulation.None 如您所见,对其他元素有一个操作,所以它有效,但对我的 innerHTML 无效。
你有什么想法,版本问题?或者与其他元素合作?

提前感谢您的宝贵时间!
祝你项目成功。

您必须绕过 angular 对危险内容施加的安全措施(HTML 内容不是由应用程序生成的)。有一项名为 DomSanitizer 的服务可让您将内容声明为安全的,从而防止 angular 过滤可能有害的内容,例如样式、类、标签等。您基本上需要使用管道通过此消毒剂传递您的内容:

<div [innerHTML]="dangerousContent | safeHtml"></div>

你的 SafeHtmlPipe 会是这样的:

@Pipe({name: 'safeHtml'})
export class SafeHtmlPipe implements PipeTransform {

  constructor(protected sanitizer: DomSanitizer) {}

  transform(value: string): SafeHtml {
    return this.sanitizer.bypassSecurityTrustHtml(value)
  }
}

DomSanitizer中还有其他bypassSecurityTrust*方法:

  • 绕过SecurityTrustScript

  • bypassSecurityTrustStyle

  • bypassSecurityTrustUrl

  • bypassSecurityTrustResourceUrl

您可以在 Angular docs 中找到更多信息。