【问题标题】:How to append html code to div element using Angular2 [duplicate]如何使用Angular2将html代码附加到div元素[重复]
【发布时间】:2016-10-30 09:00:16
【问题描述】:

我有一个 div,我必须使用 Angular2 添加一些可变的 html 代码。

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 中添加 str 字符串作为 html。

【问题讨论】:

    标签: javascript html angular angular2-template


    【解决方案1】:

    您可以像这样绑定到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>";
    
    }
    

    【讨论】:

    • 谢谢。我还有一个疑问。我通过 innerHTML 添加了一个 div 并具有(单击)功能。但是当我点击它时它不起作用。private str = "&lt;div class='EachWidget FL'&gt;&lt;div class='WidgetDataParent' (click)="widget_click($event)"&gt;&lt;div class='widgetTitleBar'&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;";
    • 是的,这行不通。您只能在 real 模板代码上拥有事件绑定。
    • 您可以动态添加组件 - 看看这个:blog.lacolaco.net/post/dynamic-component-creation-in-angular-2
    • 从技术上讲,innerHtml 不会附加,它会替换 html。
    • 尽管OP在这里使用了错误的动词,但您可以通过查看他的代码来猜出他的意思。
    猜你喜欢
    • 2017-09-22
    • 2015-11-20
    • 2021-04-18
    • 1970-01-01
    • 2023-01-16
    • 1970-01-01
    • 1970-01-01
    • 2012-08-30
    • 2018-02-10
    相关资源
    最近更新 更多