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. Looking to hire Angularjs developers in India with the most experience for the least amount of money? Hire Angular Developers using our recognized RaaS model, which offers you the best resource at your hands, with over 3+ years of experience in Angular Development.