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

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

问题描述

我想插入一些HTML,我从我的服务器上检索到angular2 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不安全指令,它只是直接将一个值赋给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?为什么我需要来包装DOM操作中的setTimeout?

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-$p$pview-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变为[内HTML。

您可以用这个试试。

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

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