2016-12-29 33 views
0

一些背景知识,如果您想跳到真正的问题,请向下滚动:-)。如何将动态组件设置为模板?

我有object小号 的一个定义的字段中的表中显示,并且一个以及定义了与每个场的每一行的一些元数据2 array秒,在这种情况下inputs

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

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

每个objectrows将迭代,以及每个objectheaders

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

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

使用两套<td>*ngIf="row.inputs"(反之亦然)给了我这个错误:

Can't have multiple template bindings on one element. Use only one attribute named 'template' or prefixed with *...

这是一个坏消息,但我得到它。

问题

在世界上最好的,我希望在的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> 

回答

0

中进行了说明如果要根据字段生成组件,最好的办法可能是创建结构指令。

例如:

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**] 
相关问题