I have an angular 2 site and I'm trying to inject some HTML with some style onto the page like this:
<div [innerHTML]="results.top3.TopThreeComments"></div>
results is the data that's returned to the page after it does a call to our web API. results.top3.TopThreeComments
is a string that looks like this:
<p><span style="text-decoration: underline;">underline</span></p>
Obviously, the styling is suppposed to underline the text inside the span, but for some reason the angular site strips the style so that the text is not underlined when it's rendered.
Why is this?
I came across a site in my google search here:
Angular2 innerHtml binding remove style attribute
It recommends using the DomSanitizer:
import { DomSanitizer } from '@angular/platform-browser'
import {PipeTransform, Pipe} from "@angular/core";
@Pipe({ name: 'safeHtml'})
export class SafeHtmlPipe implements PipeTransform {
constructor(private sanitized: DomSanitizer) {}
transform(value) {
return this.sanitized.bypassSecurityTrustHtml(value);
}
}
...and then on the page:
<div [innerHtml]="html | safeHtml"></div>
So I added the above typescript to my main component file (which drives the page) and inserted safeHtml to the innerHtml attribute of my div:
<div [innerHTML]="results.top3.TopThreeComments | safeHtml"></div>
All this did was give me the following error in the Chrome console:
Uncaught Error: Template parse errors:
The pipe 'safeHtml' could not be found ("op3.TopThreeComments">
<strong>Comments</strong><br>
<div [ERROR ->][innerHTML]="results.top3.TopThreeComments | safeHtml"></div>
</div>
"): ng:///ResultsAppModule/ResultsComponent.html@73:25
Does anyone know what I'm doing wrong. Or is there an alternative (preferably simpler) way of doing this?