使用angular2(Angular2中的一般DOM操作)将HTML从服务器插入到DOM中 [英] Inserting HTML from server into DOM with angular2 (general DOM manipulation in Angular2)

查看:104
本文介绍了使用angular2(Angular2中的一般DOM操作)将HTML从服务器插入到DOM中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将一些从服务器检索到的HTML插入到角度为2的DOM元素中。我似乎无法找出最好的/正确的方式来做到这一点。

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.

我不能把{{my_data}}放入模板中,因为角度2会自动转义HTML。

I can't just put {{my_data}} into a template because angular 2 will automatically escape the HTML.

我尝试编写一个html-unsafe指令,它直接将元素的值赋值给元素的innerHTML:

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>

这个功能很好,但我不知道这是正确的方法,而setTimeout看起来像一个奇怪的解决方法。没有setTimeout,似乎 this.elem.nativeElement 实际上并不指向DOM元素,而是指某种临时元素。

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.

是否有更多的正确的angular2方式来简单地将HTML插入到DOM中?为什么需要在setTimeout中包装DOM操作?

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?

推荐答案

阅读这篇文章 http://www.beyondjava.net/blog/angularjs-2-0-sneak-preview -data-binding / 从2014年11月起。

Reading this article http://www.beyondjava.net/blog/angularjs-2-0-sneak-preview-data-binding/ from November 2014.

ng-bind-html变成[innerHTML]。

你可以试试这个。

这篇关于使用angular2(Angular2中的一般DOM操作)将HTML从服务器插入到DOM中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆