2016-07-16 171 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

添加不同的组件 –