You might have a situation where you need to display/bind HTML code into some DOM elements.

Usually, there’s no problem in that binding, except that Angular will remove all the attributes from your HTML tags, and display them as simple string.

One solution to this is to create a Pipe and use it whenever you need the HTML to be as is (not filtered, not sanitized).

1 . First create new file to hold the pipe pipes/keep-html.pipe.ts:

ng g pipe <name> 

the pipe ts.file will be filled like this :

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

@Pipe({ name: 'safeHtml', pure: false })
export class SafeHtmlPipe implements PipeTransform {
  constructor(private sanitizer: DomSanitizer) {
  }

  transform(content) {
    return this.sanitizer.bypassSecurityTrustHtml(content);
  }
}

2. An import statement should be added (trough ‘ng generate’ function) in your app.module.ts. If not, you have to do it yourself.

import { SafeHtmlPipe } from './pipes/safe-html.pipe';
@NgModule({
  declarations: [
    SafeHtmlPipe
  ],
  bootstrap: [AppComponent]
})
export class AppModule {
}

3. Finally use that pipe in your template:

<div [innerHTML]="htmlContent | safeHtml"></div>

You are done !

Reference:

https://medium.com/

https://stackoverflow.com/questions/37076867/in-rc-1-some-styles-cant-be-added-using-binding-syntax/37076868#37076868

By Shabazz

Software Engineer, MCSD, Web developer & Angular specialist

Leave a Reply

Your email address will not be published. Required fields are marked *