In the previous post, we have seen how to bind HTML in Angular. Sometimes the HTML to bind is unsafe and Angular throws WARNING: sanitizing unsafe URL value in the browser console. This tutorial will show 2 ways how to fix it.
Let’s consider this HTML :
1 2 3 4 |
export const HTML_TEMPLATE = ` <h1>Angular Tutorials on Roufid.com</h1> <strong><a href="javascript:alert('safe html')">Hello world !</a></strong> `; |
Usage
1 |
<div [innerHTML]="htmlTemplate"></div> |
This HTML binding throws WARNING: sanitizing unsafe URL value because of href="javascript:alert('safe html').
Angular Pipe
The first solution uses Angular pipe.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
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(value: any, args?: any): any { return this.sanitizer.bypassSecurityTrustHtml(value); } } |
Then use it like this :
1 |
<div [innerHTML]="htmlTemplate | safeHtml"></div> |
Angular Directive
Another approach is to use an Angular directive :
- sanitize-html.directive.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
import {Directive, HostBinding, Input} from '@angular/core'; import {DomSanitizer, SafeHtml} from '@angular/platform-browser'; @Directive({ selector: '[sanitizeHtml]' }) export class SanitizeHtmlDirective { @Input() sanitizeHtml: string; constructor(private sanitizer: DomSanitizer) { } @HostBinding('innerHtml') get innerHtml(): SafeHtml { return this.sanitizer.bypassSecurityTrustHtml(this.sanitizeHtml); } } |
1 |
<div [sanitizeHtml]="htmlTemplate"></div> |
The tutorial source code is available on Github. Download the source