Skip to content

Instantly share code, notes, and snippets.

@klihelp
Last active March 24, 2021 13:41
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save klihelp/4dcac910124409fa7bd20f230818c8d1 to your computer and use it in GitHub Desktop.
Save klihelp/4dcac910124409fa7bd20f230818c8d1 to your computer and use it in GitHub Desktop.
Angular 2 - Add safeHtml for innerHTML
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { SafeHtmlPipe } from "./pipes"
@NgModule({
declarations: [
SafeHtmlPipe,
],
imports: [
],
providers: [
],
bootstrap: [AppComponent]
})
export class AppModule {}
// Load html in Angular 2
// In content.html use:
// <div [innerHTML]="post.content.rendered | safeHtml " class="entry-body"></div>
import { Pipe, PipeTransform } from "@angular/core";
import { DomSanitizer } from "@angular/platform-browser";
@Pipe({name: 'safeHtml'})
export class SafeHtmlPipe implements PipeTransform {
constructor(private sanitized: DomSanitizer) {
}
transform(value: string) {
return this.sanitized.bypassSecurityTrustHtml(value);
}
}
@jmmaranan
Copy link

jmmaranan commented Jan 11, 2018

Thanks for this - in Angular 4+, the ng-compiler complains that the exported class cannot be named, ex Return type of public method from exported class has or is using name 'SafeHtml' from external module - adding an additional SafeHtml import to your pipe.safehtml.ts example would help a lot for future readers:

import { DomSanitizer, SafeHtml } from '@angular/platform-browser';

@debugly
Copy link

debugly commented Oct 8, 2018

Safe value must use [property]=binding

<span [innerHTML]="b.buildInfo | safeHtml"></span>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment