3

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 Answer 1

5

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>
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Chandan, worked perfectly, one additional change I had to make though to your code is to add SafeHtml to also import from the platform-browser(not just the DomSanitizer)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.