Last active
March 24, 2021 13:41
-
-
Save klihelp/4dcac910124409fa7bd20f230818c8d1 to your computer and use it in GitHub Desktop.
Angular 2 - Add safeHtml for innerHTML
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 {} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); | |
} | |
} |
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
Thanks for this - in Angular 4+, the
ng-compiler
complains that the exported class cannot be named, exReturn type of public method from exported class has or is using name 'SafeHtml' from external module
- adding an additionalSafeHtml
import to yourpipe.safehtml.ts
example would help a lot for future readers: