For security reason, Angular prevents attackers from injecting malicious client-side scripts into web pages.
For Bypassing Angular protection
Some applications genuinely need to include executable script or styles. In such cases, you disable Angular’s built-in sanitization. To do that we create a pipe and inject DomSanitizer service to the constructor of the pipe and call one of the following methods depending upon the context to mark the value safe.
- bypassSecurityTrustHtml
- bypassSecurityTrustScript
- bypassSecurityTrustStyle
- bypassSecurityTrustUrl
- bypassSecurityTrustResourceUrl.
You need to create Pipe for it below are the code for same:
htmlParse.ts:
import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer, SafeHtml, SafeStyle, SafeScript, SafeUrl, SafeResourceUrl } from '@angular/platform-browser';
@Pipe({
name: 'safe'
})
export class SafePipe implements PipeTransform {
constructor(protected sanitizer: DomSanitizer) {}
public transform(value: any, type: string): SafeHtml | SafeStyle | SafeScript | SafeUrl | SafeResourceUrl {
switch (type) {
case 'html': return this.sanitizer.bypassSecurityTrustHtml(value);
case 'style': return this.sanitizer.bypassSecurityTrustStyle(value);
case 'script': return this.sanitizer.bypassSecurityTrustScript(value);
case 'url': return this.sanitizer.bypassSecurityTrustUrl(value);
case 'resourceUrl': return this.sanitizer.bypassSecurityTrustResourceUrl(value);
default: throw new Error(`Invalid safe type specified: ${type}`);
}
}
}
then you need to declare it in your module.ts file:
import { SafePipe } from '../pipes/htmlparse';
@NgModule({
declarations: [
AppComponent,
SafePipe
],
imports: [
BrowserModule,
HttpModule,
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
and then you can use pipe with your innerHtml attribute:
<div [innerHTML]="data.message | safe:'html'"></div>