[英]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.