【问题标题】:How do you set dynamic components to a template?如何将动态组件设置为模板?
【发布时间】:2016-12-29 10:50:59
【问题描述】:

一些背景知识,如果您想跳到真正的问题,请向下滚动:-)。

我有两个arrays 和objects 一个定义要在表格中显示的字段,另一个定义包含每个字段的每一行以及一些元数据,在本例中为 inputs

headers = [
    {
        field: 'a'
    },
    {
        field: 'b'
    }
]

rows = [
    {
        a: "foo", 
        b: "bar", 
        inputs: false
    },
    {
        a: "foo",
        b: "bar", 
        inputs: true
    }
]

rows 中的每个 object 以及 headers 中的每个 object 都将被迭代

<table>
    <tr *ngFor="let row of rows">
        <td *ngFor="let cell of headers" [innerHtml]="row[cell.field]">
        </td>
    </tr>
</table>

只要,一切都好。 但是,如果我想要取决于 row.inputs 值的动态输入字段 - 应该如何解决?

使用两组&lt;td&gt;*ngIf="row.inputs"(反之亦然)会给我这个错误:

一个元素上不能有多个模板绑定。仅使用一个名为“模板”或前缀为 *...的属性...

这很糟糕,但我明白了。

问题

在最好的情况下,我想在 innerHtml 中使用一个函数,它返回一个输入组件,但它会是什么样子?

例如:

在我的Component 中,我添加了一个名为getDataOrInput 的函数

  getDataOrInput(row, field): string | HTMLElement {
    if(row.inputs){
        /* 
        * Generate a Component based on field, and return HTML ?  
        */
    } else {
        return row[field]
    }
}

在 HTML 中

<table>
    <tr *ngFor="let row of rows">
        <td *ngFor="let cell of headers" 
            [innerHtml]="getDataOrInput(row,cell.field)">
        </td>
    </tr>
</table>

【问题讨论】:

    标签: angular angular2-template angular2-components


    【解决方案1】:

    对于您的错误消息*ngIf and *ngFor on same element causing error,有一个简单的解决方法

    Angular 2 dynamic tabs with user-click chosen components 中解释了动态组件的另一种方法

    【讨论】:

      【解决方案2】:

      如果你想基于一个字段生成一个组件,你最好的选择可能是创建一个结构指令。

      例如:

      const factory = this._resolver.resolveComponentFactory(**SomeComponent**);
      
      // Make the Component with a factory and index (tells angular where to place component)
      
      const componentRef = this._viewContainer.createComponent(factory, i);
      
      // then you can tap into the instance of that component like so:
      componentRef.instance.[**SomeInputName**]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-07-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多