12

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?

DilumN
  • 2,889
  • 6
  • 30
  • 44
imagio
  • 1,390
  • 2
  • 16
  • 27

2 Answers2

8

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.

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
nada
  • 972
  • 5
  • 22
  • 2
    While this works for simple HTML tags like Hello! it does not work for Angular directives you have created yourself. In Angular 1.x you used $sce.trustAsHTML() combined with a custom directive that called $compile to compile Angular directives in your HTML. We need to know the equivalent of this in Angular 2. – Vern Jensen Sep 01 '15 at 20:31
  • 2
    I think that it is now `[innerHTML]`. – R891 Jan 22 '16 at 01:50
  • @VernJensen I have the same issue with custom directives, have you solved it ? – Omar Hassan Apr 24 '16 at 06:26
  • No, I realized that for my purposes, I could use an *ngFor loop to iterate over a series of custom objects that specify the HTML elements I want, with a series of *ngIf statements inside the loop -- one for each HTML directive I want to be able to create. (For instance, one for a – Vern Jensen May 06 '16 at 01:25
0

I was able to do it in the following way:

<td bind-inner-html="my_data"></td>