I would like to insert some HTML that I retrieve from my server into a DOM element in angular2. I can't seem to figure out the best/correct way to do this.
I can't just put {{my_data}} into a template because angular 2 will automatically escape the HTML.
I have attempted to write an html-unsafe directive which just assigns a value directly to innerHTML of an element:
/// <reference path="../../typings/typings.d.ts" />
import {Directive} from 'angular2/angular2';
import {ElementRef} from 'angular2/core';
@Directive({
selector: "[html-unsafe]",
properties: ['htmlUnsafe']
})
export class HtmlUnsafe{
constructor(private elem: ElementRef){
}
set htmlUnsafe(value){
setTimeout(() => {
this.elem.nativeElement.innerHTML = value;
},0);
}
}
So now in my template I have something like
<td [html-unsafe]="my_data"></td>
This works, but I am not sure it is the correct way to do this and the setTimeout seems like an odd workaround. Without the setTimeout it appears that this.elem.nativeElement
does not actually refer to the DOM element but to some sort of temporary element.
Is there a more "correct" angular2 way to simply insert HTML into the DOM? Why do I need to wrap the DOM manipulation in a setTimeout?
Reading this article http://www.beyondjava.net/blog/angularjs-2-0-sneak-preview-data-binding/ from November 2014.
ng-bind-html becomes [innerHTML].
You can try with this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With