[英]Angular list with generic component as list item
假设我有一个“ParentComponent”,它有一个项目列表(假设作为输入)并且需要呈现列表中的元素。 我需要这个父组件是可重用的,它支持的自定义之一是选择它用于呈现列表项的模板(或组件)。 用于子列表项的组件可以是任何东西,只要它可以呈现提供给它的列表项作为输入(模板可以正确引用项的属性)。 这在 React 等框架中是可能的,所以我的问题是在 Angular 中是否也有可能,以及如何做到这一点?
我想象父组件将自定义组件作为输入,以及项目
@Input()
items: Array<ItemType>;
@Input()
componentForRenderingStuff: ?;
模板是这样的
<div class="wrapper">
<!-- ...stuff -->
<div class="list-item" *ngFor="let i of items">
<component-for-rendering-stuff [item]="i"></component-for-rendering-stuff>
</div>
</div>
这意味着在另一个模板中使用父组件就像
<app-parent-component [items]="items" [componentForRenderingStuff]="SomeComponent"></app-parent-component>
这样的事情可能吗? 我查看了ng-content
但我无法让它与*ngFor
。
正如爱德华在他的评论中所建议的那样,可以使用动态组件加载来实现该行为。
我在 npm 上找到了一些解决了这个问题的第三方库,由于时间和简单性,我使用了最吸引人的用户统计数据: https : //www.npmjs.com/package/ng-dynamic-component
简而言之,通用列表组件如下所示
@Component({
selector: 'app-list',
template: `
<div *ngFor="let item of items">
<ndc-dynamic
[ndcDynamicComponent]="listItemComponent"
[ndcDynamicInputs]="{ input: item.data }"
></ndc-dynamic>
</div>
`,
styleUrls: ['...'],
})
export class ClickableVerticalListComponent {
@Input()
listItemComponent: any;
@Input()
items: Array<any>;
constructor() {}
}
如果我们想将列表与列表项的特定自定义组件一起使用,我们会这样做:
@Component({
selector: '...',
template: `
<app-list
[items]="items"
[listItemComponent]="ExampleComponent"
></app-list>
`,
styleUrls: ['...'],
})
export class ParentComponent {
ExampleComponent = ExampleComponent;
items: [{ data: ... }, { data: ... }];
constructor() {}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.