【问题标题】:Angular strips out data attribute from innerHTMLAngular 从 innerHTML 中去除数据属性
【发布时间】:2023-03-29 04:22:01
【问题描述】:

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

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

因此,为了将其显示为 HTML,我使用了 interHTML 属性:

<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);
    });

【问题讨论】:

标签: html angular typescript


【解决方案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>`,
})

【讨论】:

  • 这确实有所作为,但没有解决问题 - 见上文
  • 您是否使用了 css 选择器的数据属性?
  • 它完全按照我的测试工作,如果您使用 css 选择数据属性,我认为您应该将 css 移动到您的全局样式
  • 我是的,人类
  • 当我正确声明我的管道时 - 这解决了问题
猜你喜欢
  • 2018-07-11
  • 2020-01-02
  • 2019-07-26
  • 2021-01-24
  • 1970-01-01
  • 2017-09-14
  • 2018-05-22
  • 2021-11-08
  • 2015-12-07
相关资源
最近更新 更多