You can do the one trick here, so you don't need to write your toSafeHtml function again and again,
First create one service like
import { Injectable } from "@angular/core";
@Injectable({
providedIn: "root",
})
export class YourServiceName {
toSafeHtml(value): any {
return new DOMParser().parseFromString(value, "text/html").documentElement.textContent;
}
}
Then you have to add dependency in constructor of your component where you need to use above function
constructor(public yourServiceName: YourServiceName) {
}
And then you can use it in you template like
<div [innerHtml]="yourServiceName.toSafeHtml(loaderTitle)"></div>
Edit 1:
I don't want repeat the same for each and every component
You can also create a attribute directive to achieve your goal
import { Directive, ElementRef, HostListener, Input, OnInit } from '@angular/core';
@Directive({
selector: '[appHtmlParser]'
})
export class HtmlParserDirective implements OnInit {
@Input('html') html: any;
constructor(private el: ElementRef) {
}
ngOnInit(): void {
this.el.nativeElement.textContent = this.toSafeHtml(this.html);
}
toSafeHtml(value): any {
return new DOMParser().parseFromString(value, "text/html").documentElement.textContent;
}
}
And then you can use it in your template like
<div appHtmlParser [html]="loaderTitle"></div>
Stackblitz Demo
[innerHtml]="toSafeHtml(loaderTitle)"or any better way