2016-12-29 94 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**] 
相關問題