Angular中的动态子组件 [英] Dynamic Child Component in Angular
问题描述
我正在为元素列表构建具有一致设计模式的应用程序.如果我有一个类型为A的对象,则创建一个 AComponent
接受 a
作为输入,然后创建另一个组件以遍历A的列表,即 AListComponent
.然后,如果我有一个对象B,我需要做同样的事情.看来我应该能够使 ObjectListComponent
传入要迭代的对象的类,以使代码保持DRY.
I am building an app with a consistent design pattern for lists of elements. If I have an object of type A, I create AComponent
which accepts a
as an input, then create another component to iterate over a list of A's, AListComponent
. Then if I have an object B, I need to do the same thing. It seems like I should be able to make an ObjectListComponent
passing in the class of the object I want to iterate over, to keep my code DRY.
例如,给定
组件控制器
...
@Input
a: A;
...
AComponent HTML
<div>{{ a.name }}</div>
AListComponent控制器
...
@Input()
aList: A[];
...
AListComponent HTML
<div *ngFor='let aObj of aList'>
<app-a [a]='aObj'></app-a>
</div>
如何将 AListComponent
抽象为 ObjectListComponent
?
ObjectListComponent控制器
...
@Input()
type: any;
@Input()
objects: <type>[]
objectComponent: any;
ngOnInit () {
this.objectComponent = <get object component from type>
}
ObjectListComponent HTML
<div *ngFor='let obj of objects'>
<app-objectComponent [object]='obj'></app-objectComponent>
</div>
其中 ObjectListComponent
将用作
...
<app-object-list [type]='A' objects='aList'></app-object-list>
...
推荐答案
感谢提供演示代码,主要逻辑在 object-list.components.ts
ngAfterViewInit(){
const component_obj = this.getComponentType(this.objects[0]);
this.containers.map(
(vcr: ViewContainerRef, index: number) => {
const factory = this.resolver.resolveComponentFactory(
component_obj);
const componentRef = vcr.createComponent(factory);
componentRef.instance['data'] = this.objects[index];
this.cd.detectChanges()
}
)
}
基本上,我要做的是:
-
a.component.html :处理对象
接口A
b.component.html :处理类型为接口B
您可以在 home.component.html
显示组件A
<app-object-list [objects]='aList'></app-object-list>
显示组件B
<app-object-list [objects]='bList'></app-object-list>
您可以改进检查和确定类型的逻辑.那部分代码可以改进
You can improve the logic to check and determine the type. That part of the code can be improved
这篇关于Angular中的动态子组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!