2016-07-16 138 views
0

我如何設置動態名稱爲angular 2組件?Angular 2組件動態名稱

我有我的模板下面的代碼:

<{{component} [data]="data" [anotherData]="anotherData"></{{component}}> 

我希望你在我的類中定義組件名稱

component: string = 'component'; 

因爲現在我有一個錯誤:

Uncaught (in promise): Template parse errors: 
Unexpected closing tag "{{component}" (" 
+0

一種可能的方法http://stackoverflow.com/questions/36325212/angular-2-dynamic-tabs-with-user-click-chosen-components/36325468#36325468 –

回答

0
<div [ngSwitch]="contactService.contact.cat"> 
     <div *ngSwitchWhen="'person'"> 
      <persons-edit [primary]="true"></persons-edit> 
     </div> 
     <div *ngSwitchWhen="'business'"> 
      <businesses-edit [primary]="true"></businesses-edit> 
     </div> 
     <div *ngSwitchWhen="'place'"> 
      <places-edit [primary]="true"></places-edit> 
     </div> 
    </div> 

這是我在我的應用程序中使用的。我定義了三個組件,並使用開關顯示我想要的組件。我從服務中獲取選擇,但可以從根組件獲取。事情是這樣的:

@Component { 
    selector: 'dynamic-component', 
    .... 
} 

export class DynamicComponent{ 
@Input selectedcomponent : string; 

} 

在模板然後使用它:

<dynamic-component [selectedcomponent]="person"></dynamic-component> 

而不是使用的 「selectedcomponent」 的服務,開關和。

1

你不能按照您嘗試執行的方式爲組件動態分配名稱。 但是,您可以動態地將ID分配給您的元素[attr.id]="id_string_expression" 您很可能可以通過這種方式解決您的問題。 喜歡的東西:

<my-component [attr.id]="name+number" [data]="data" [anotherData]="anotherData"></my-component> 
+0

它不幫助我。因爲我想插入不同的組件。例如'組件'可以是'書'或'文章'。並且想要在模板中渲染所需的組件。 –

+0

在這種情況下,請看* ngIf。 – hholtij

+0

是的。但它不能幫助我/ –

2

答案很簡單你不能

在定義組件時,您必須聲明該組件的名稱(即選擇器屬性)以及類名稱。沒有聲明組件名稱,你不能創建組件。

所以在你的情況下,有選擇是你創建沒有。的組件,並在需要時隨時調用該組件或創建該組件的動態輸入值,以便根據需要設置動態值並獲得usng @Input。因爲每個組件都有差異。模板和邏輯,所以更好的是創建新組件並根據需要使用。

毫無疑問,你可以設置動態數據到該組件,如ID的名稱,自定義輸入等等。 希望它清除一切,如果不在這裏評論!

+0

'ViewContainerRef.createComponent()'可能是一個選項 –

+0

選項爲什麼? ViewContainerRef.createComponent()'的用法? –

+0

添加不同的組件 –