Inserting HTML via Angular 2: Use of DomSanitizationService & bypassSecurityTrustHtml

I recently created a pipe to make it simpler to mark values as trusted/safe.

You can use it to bypass html sanitization like this in templates:

<div [innerHTML]="product.description | safe: 'html'"></div>

Or if you need to bypass style sanitization:

<div [style.background-image]="'url(' + product.imageUrl + ')' | safe: 'style'"></div>

‘script’, ‘url’ and ‘resourceUrl’ is also supported. Read more here: https://angular.io/docs/ts/latest/api/platform-browser/index/DomSanitizationService-class.html

Here’s the SafePipe code:

import {Pipe} from '@angular/core';
import {DomSanitizationService, SafeHtml, SafeStyle, SafeScript, SafeUrl, SafeResourceUrl} from '@angular/platform-browser';

@Pipe({
	name: 'safe'
})
export class SafePipe {

	constructor(protected _sanitizer: DomSanitizationService) {

	}

	public transform(value: string, 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(`Unable to bypass security for invalid type: ${type}`);
		}
	}

}

14 Likes