How to display a typescript string variable containing html content on the template as an element, and not string?

Viewed 6270

I have an angular application, I have the following in component typescript:

field: string;
  constructor() { 
    this.field = "Hello, I am <b>happy</b><br><br><input type='text' value='hello' />"
  }

and in my html template for the component I have this:

<div [innerHTML]="field"></div>

I am expecting an output:

Hello, I am happy(happy in bold)

[Text input field here]

Instead the entire input tag is omitted. Any idea how to render html content like this onto a template in angular?

1 Answers

You will have to trust the HTML first before injecting it. You have to use the DomSanitizer for such a thing. An h3 or p or div element is considered safe. An input element is not.

You can create a pipe and use it where ever you need it.

import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';

@Pipe({
    name: 'sanitizeHtml'
})
export class SanitizeHtml implements PipeTransform  {

   constructor(private _sanitizer: DomSanitizer){}  

   transform(v: string) : SafeHtml {
      return this._sanitizer.bypassSecurityTrustHtml(v); 
   } 
} 

Now in you html you can call the pipe in this way :

<div [innerHTML]="field | sanitizeHtml"></div>
Related