2016-06-28 82 views
1

我有一个div,我必须添加一些HTML代码在变量中使用Angular2。如何将html代码添加到使用Angular2的div元素

import {Component,Input,ViewChild,ElementRef,OnInit} from 'angular2/core'; 

@Component({ 
    selector: 'my-view', 
    template: ` 
    <div #myDiv>{{str}}</div> 
`, 
    styleUrls:['src/css/thedata.css'] 
}) 
    export class AngularComponent{ 
       private str = "<div class='EachWidget FL'><div class='WidgetDataParent'><div class='widgetTitleBar'></div></div></div>"; 

     } 

我必须在名为myDiv的div中添加字符串作为html。

回答

3

您可以绑定到innerHTML属性是这样的:

import {Component,Input,ViewChild,ElementRef,OnInit} from 'angular2/core'; 

@Component({ 
    selector: 'my-view', 
    template: ` 
    <div [innerHTML]="str" #myDiv></div> 
`, 
    styleUrls:['src/css/thedata.css'] 
}) 
export class AngularComponent{ 
    private str = "<div class='EachWidget FL'><div class='WidgetDataParent'><div class='widgetTitleBar'></div></div></div>"; 

} 
+0

感谢。我还有一个疑问。我已经通过innerHTML添加了一个div,并具有(单击)功能。但是当我点击它不工作.'private str =“

”;' – Lucifer

+0

是的,这是行不通的。您只能在** real **模板代码上进行事件绑定。 – rinukkusu

+0

然而,你可以动态地添加组件 - 看看这个:http://blog.lacolaco.net/post/dynamic-component-creation-in-angular-2/ – rinukkusu