Inserting HTML from server into DOM with angular2 (general DOM manipulation in Angular2) [duplicate]

Question!

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?



Answers

I was able to do it in the following way:



This video can help you solving your question :)
By: admin