网站搜索

html - Angular 从 innerHTML 中去除数据属性


我有一个从 API 端点返回的字符串,如下所示:

If you died tomorrow, your wife <span class='person' data-relationship='Relationship.Wife' data-avatarid='1212'>Alice</span> will lose everything.

所以为了将其显示为 HTML,我正在使用 innerHTML 属性:

<p *ngFor="let con1Died of consequences?.client1Died" [innerHTML]="con1Died"></p>

但是这会以去掉数据属性的方式输出到浏览器,如下所示:

<p _ngcontent-smy-c63="">If you died tomorrow, your wife <span class="person">Alice</span> will lose everything.</p>

我如何才能输出带有数据属性的内容?有什么方法可以做到吗?

编辑:所以我尝试了下面的 HTML 清理技术,但 CSS 仍然没有应用:

this.reportsService.getConsequences().subscribe(res => {
      // Load the consequences to angular
      this.consequences = res;
      this.client1Died = new Array();
      this.consequences.client1Died.forEach(element => {
        const safehtml = this.sanitized.bypassSecurityTrustHtml(element);
        this.client1Died.push(safehtml);
      });
      console.log(this.client1Died);
    });

答案#1

创建一个管道来净化 HTML:

@Pipe({ name: 'safeHtml'})
export class SafeHtmlPipe implements PipeTransform  {
    constructor(private sanitized: DomSanitizer) {}
    transform(value) {
        return this.sanitized.bypassSecurityTrustHtml(value);
    }
}

@Component({
    selector: 'my-app',
    template: `<div [innerHTML]="content | safeHtml"></div>`,
})