Style Not Working For innerHTML In Angular

Hello, friends in this article we will discuss the style not working for innerHTML in angular. When we are generating HTML on the server-side and binding HTML using innerHTML on the angular side then angular removes all styles attributes. here I have provided one solution for this we add Angular sanitizes and the added HTML dynamically. so let’s start

 

First, we need to create a new Pipe for safeHtml using the following command:

ng g pipe safeHtml

Now, add the following code in safeHtml pipe:

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

@Pipe({
  name: 'safeHtml',
})
export class SafeHtmlPipe implements PipeTransform {

  constructor(private sanitizer:DomSanitizer){}

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

}

Now add declarations in the app.module.ts file.

@NgModule({
  declarations: [
    SafeHtmlPipe,
]

And the last thing in the Html file where we are using innerHTML tag and add your pipe like below:

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

I hope this article helps you and you will like it.

Submit a Comment

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

Footer Logo

Subscribe

Select Categories