Angular built-in supports vulnerabilities and attacks in a web application like cross site scripting, however sometimes in our application we want to render the html string through bypassing the security of angular.
To bypass the security, angular itself provides some methods and directives by which we can render or show html string in angular.
There is two ways to render the html string
- innerHTML directive – Render only simple html tags and style tags, and remove style attributes and script tag
- DomSanitizer – Render html with style tag and style tags but also remove scripts
Simple syntax for innerHTML
<div [innerHTML]="html"></div>
Simple syntax for DomSanitizer
this.safehtmlStr=dom.bypassSecurityTrustHtml(this.html);
Example 1 : innerHTML to render the string
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'newapp';
html:string="<p style='color:red'>String with color:red </p><a href='https://google.com'>google.com</a><script>alert('aa')</script>"
constructor(){
}
}
and html
<h2>Simple HTML only without style(Removed)</h2>
<div [innerHTML]="html"></div>
Example 2 : innerHTML to render the string
import { Component } from '@angular/core';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'newapp';
html:string="<style>a{ color:green}</style><p style='color:red'>String with color:red </p><a href='https://google.com'>google.com</a><script>alert('aa')</script>"
safehtmlStr:SafeHtml;
constructor( public dom:DomSanitizer){
this.safehtmlStr=dom.bypassSecurityTrustHtml(this.html);
}
}
and html
<h2> HTML With style</h2>
<div [innerHTML]="safehtmlStr"></div>
Output :
As you can see we have used here DomSanitizer
and its method bypassSecurityTrustHtml
to sanitize the html string but it removes the script tag and only keeps html and inline style.
Create a pipe for safe html for global use
we can also create a pipe for safe html so we can use it globally in our app as below
import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
@Pipe({
name: 'safehtml'
})
export class SafePipe implements PipeTransform {
constructor(protected sanitizer: DomSanitizer) {}
public transform(value: any): SafeHtml {
return this.sanitizer.bypassSecurityTrustHtml(value);
}
}
and in html
<h2>HTML with pipe</h2>
<div [innerHTML]="html | safehtml"></div>
Live Example:
Also Read : How to Insert script tag dynamically in angular ?