typescript 使用 angular2 将服务器中的 HTML 插入 DOM(Angular2 中的一般 DOM 操作)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31146472/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Inserting HTML from server into DOM with angular2 (general DOM manipulation in Angular2)
提问by imagio
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.
我想将从我的服务器检索到的一些 HTML 插入到 angular2 中的 DOM 元素中。我似乎无法找出最好/正确的方法来做到这一点。
I can't just put {{my_data}} into a template because angular 2 will automatically escape the HTML.
我不能只是将 {{my_data}} 放入模板中,因为 angular 2 会自动转义 HTML。
I have attempted to write an html-unsafe directive which just assigns a value directly to innerHTML of an element:
我试图编写一个 html-unsafe 指令,它只是直接为元素的 innerHTML 赋值:
/// <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.
这有效,但我不确定这是正确的方法,而且 setTimeout 似乎是一种奇怪的解决方法。如果没有 setTimeout,它似乎this.elem.nativeElement
实际上并不是指 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?
是否有更“正确”的 angular2 方法来简单地将 HTML 插入到 DOM 中?为什么我需要将 DOM 操作包装在 setTimeout 中?
回答by nada
Reading this article http://www.beyondjava.net/blog/angularjs-2-0-sneak-preview-data-binding/from November 2014.
从 2014 年 11 月开始阅读这篇文章http://www.beyondjava.net/blog/angularjs-2-0-sneak-preview-data-binding/。
ng-bind-html becomes [innerHTML].
ng-bind-html becomes [innerHTML].
You can try with this.
你可以试试这个。
回答by peter.svintsitskiy
I was able to do it in the following way:
我能够通过以下方式做到这一点:
<td bind-inner-html="my_data"></td>