Angular 6使用管道将字符串转换为HTML

时间:2020-06-03 10:36:04

标签: javascript angular typescript angular6

我的输入字符串是

  html:string="<a role="button" class=" fas fa-trash-alt fa-1x" title="Remove Link" href="#"></a>"

我希望将其转换为原始html

管道:

import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser'
@Pipe({
  name: 'htmldecoder'
})
export class HtmldecoderPipe implements PipeTransform {
  constructor(private sanitized: DomSanitizer) { }
  transform(value) {
    return this.sanitized.bypassSecurityTrustHtml(value);
  }

}

HTML代码:

<div>
    <div [innerHtml]="html | htmldecoder">
    </div>
</div>

进入UI的输出是

<a role="button" class="fas fa-trash-alt fa-1x" title="Remove Link" href="#"></a>

预期输出应为按钮

1 个答案:

答案 0 :(得分:0)

在您的代码中进行以下更改即可使用,对于自解释而言,代码非常简单

app.component.ts

  html = `html:string="&lt;a role="button" class=" fas fa-trash-alt fa-1x" title="Remove Link" href="#"&gt;aditya&lt;/a&gt;"`;

管道

  transform(value) {
    value = value.substring(13, value.length-1);
     var doc = new DOMParser().parseFromString(value, "text/html");
     const value123 = doc.documentElement.textContent;
    return this.sanitized.bypassSecurityTrustHtml(value123);
  }

app.component.html

<div [innerHTML]="html | htmldecoder">