Angular 2组件动态名称

时间:2016-07-16 13:31:13

标签: angularjs typescript angular

如何将动态名称设置为angular 2组件?

我的模板中有下一个代码:

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

我想在我的班级中定义componentName

component: string = 'component';

因为现在我有下一个错误:

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

3 个答案:

答案 0 :(得分:2)

答案只是你不能 !!

在定义组件时,必须声明该组件的名称(即选择器属性)以及类名。如果没有声明组件名称,则无法创建组件。

所以在你的情况下,有选项是你创建没有。组件和调用时,只要您需要该组件或创建该组件的动态输入值,以便根据需要设置您的动态值并获得@Input。因为每个组件都有差异。模板和逻辑也是如此,因此更好的是创建新组件并根据需要使用。

是的,毫无疑问,你可以动态地将数据设置到该组件,如ID,名称,自定义输入等。 如果不在这里评论,希望它能清除所有内容!

答案 1 :(得分:1)

您无法按照尝试的方式为组件动态分配名称。 但是,您可以使用[attr.id]="id_string_expression"为元素动态分配ID 你最有可能以这种方式解决你的问题。 类似的东西:

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

答案 2 :(得分:1)

<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>

而不是使用服务,打开&#34; selectedcomponent&#34;。

相关问题