[英]Angular 2 component dynamic name
如何將動態名稱設置為角度2組件?
我的模板中有下一個代碼:
<{{component} [data]="data" [anotherData]="anotherData"></{{component}}>
我想在我的類中定義componentName
component: string = 'component';
因為現在我有下一個錯誤:
Uncaught (in promise): Template parse errors:
Unexpected closing tag "{{component}" ("
答案就是你不能 !
在定義組件時,必須聲明該組件的名稱(即選擇器屬性)以及類名。 如果沒有聲明組件名稱,則無法創建組件。
所以在你的情況下有選項是你創建否。 組件和調用只要您需要該組件或創建該組件的動態輸入值,以便根據需要設置您的動態值並獲取@Input
。 因為每個組件都有差異。 模板和邏輯,所以更好的是創建新的組件並根據需要使用。
是的,毫無疑問,您可以動態設置數據到ID,名稱,自定義輸入等組件等。如果不在這里評論,希望它清除所有內容!
您無法按照嘗試的方式為組件動態分配名稱。 但是,你可以使用[attr.id]="id_string_expression"
動態地為你的元素分配id。你最有可能以這種方式解決你的問題。 就像是:
<my-component [attr.id]="name+number" [data]="data" [anotherData]="anotherData"></my-component>
<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”。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.