Angular 6 convert string to an Html using pipe

Viewed 3858

My input string is

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

I want this to be converted into an raw html

Pipe:

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 Code :

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

The output getting in UI is

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

Expected Output Should be the Button

1 Answers

Make this following changes in your code and it will work, the code quite simple for self-explanation

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;"`;

pipe

  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">
Related