【问题标题】:Angular 2 component dynamic nameAngular 2 组件动态名称
【发布时间】:2016-11-19 14:02:39
【问题描述】:

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

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

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

我想在我的班级中定义 componentName

component: string = 'component';

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

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

【问题讨论】:

标签: angularjs typescript angular


【解决方案1】:

您不能按照您尝试的方式为组件动态分配名称。 但是,您可以使用 [attr.id]="id_string_expression" 为您的元素动态分配 ID 您很可能可以通过这种方式解决您的问题。 比如:

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

【讨论】:

  • 这对我没有帮助。因为我想插入不同的组件。例如,“组件”可以是“书”或“文章”。并且想要在模板中呈现所需的组件。
  • 在这种情况下,请查看 *ngIf。
  • 是的。但它不能帮助我/
【解决方案2】:

答案很简单你不能!!

在定义组件时,您必须声明该组件的名称(即选择器属性)以及类名。不声明组件名就不能创建组件。

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

是的,毫无疑问,您可以为该组件动态设置数据,例如 ID、名称、自定义输入等。 如果不在这里发表评论,希望它能清除一切!

【讨论】:

  • ViewContainerRef.createComponent() 可能是一个选项
  • 选项有什么用? ViewContainerRef.createComponent() 的用法?
  • 添加不同的组件
  • 对不起,我对此一无所知。肯定会读到这个:)如果你对这个答案有一些额外的说明,你可以编辑我的答案。
  • 我目前正在使用手机。我在问题下方的评论中添加了一个链接。
【解决方案3】:
<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”。

【讨论】:

    猜你喜欢
    • 2017-04-12
    • 1970-01-01
    • 2017-04-04
    • 2018-06-06
    • 1970-01-01
    • 2017-05-03
    • 2019-03-29
    • 2021-05-16
    • 2020-03-18
    相关资源
    最近更新 更多