问题描述
假设我有一个“ ParentComponent”,它具有一个项目列表(假设作为输入),并且需要呈现列表中的元素。我需要此父组件可重用,并且它支持的自定义之一是选择用于呈现列表项的模板(或组件)。用于子级列表项的组件可以是任何东西,只要它可以将指定给它的列表项作为输入呈现(模板可以正确地引用该项的属性)。在诸如React之类的框架中这是可能的,所以我的问题是在Angular中是否也可能,以及如何做到这一点?
我想象父组件将自定义组件作为输入以及各项
m
模板是这样的
@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
配合使用。
解决方法
正如爱德华(Edward)在其评论中建议的那样,可以通过动态组件加载来实现这种行为。
我在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>
`,})
export class ParentComponent {
ExampleComponent = ExampleComponent;
items: [{ data: ... },{ data: ... }];
constructor() {}
}