Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 299
imagio Avatar asked Jun 30 '15 19:06

imagio


1 Answers

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.

like image 100
nada Avatar answered Sep 22 '22 18:09

nada