在 Angular 4 中,我可以通过编程方式更改模板中使用的组件类型吗?

In Angular 4, can I programmatically change the type of component being used in a template?

我有一个组件(我们称它为 ListComponent),其目的是编辑列表。它允许用户添加、删除和重新排序元素。它的模板看起来像这样:

<div> <!-- Some Buttons --> </div>
<ul>
    <li *ngFor="element in dataArray">
        <string-editor [(NgModel)]=element></string-editor>
        <!-- More Buttons -->
    </li>
</ul>

<string-editor> 也是一个带有模板的自定义组件,它基本上只是一个带有一些样式的输入组件。我想要做的是有多个版本的 ListComponent 可以处理不同类型的数据(例如数字,具有多个字段的自定义对象。)为此,我希望能够将 <string-editor> 替换为带有另一个组件 class 的模板(比如 <number-editor><my-custom-object-editor>。)它们都支持 NgModel。我研究了动态组件创建,但似乎无法将其用于 *ngFor 的变更检测。

那么,总而言之,有没有办法以编程方式将 <string-editor> 更改为另一个标签?如果没有,有没有一种方法可以将动态组件创建与 *ngFor 的变更检测结合使用?

你能做的是。

如果您可以确定需要使用哪种类型的组件,请使用 ng 开关。或者你也可以写一个 Ng if else

NgSwitch https://angular.io/api/common/NgSwitch ng if else https://angular.io/api/common/NgIf