我想在 Angular5 中创建可重用的 SortedList 组件。该列表应接受任何列表项(对象)数组作为属性。从 ListContainer 组件我想使用列表并传递一个列表项模板,如下所示:
<div class='list-container'>
<SortedList [items]='getListItems()' [categories]='getSortCategories()' >
<ACustomItem [item]='item'></AcustomItem>
</SortedList
<div>
ACustomItem
将是接受 [item] 的任何组件,html 会因实现而异。在我的 SortList 中,我有:
<div class='sorted-list'>
<div class='sorted-list__header'>
<div class='sorted-list__header-title'>{{title}}</div>
<select [(ngModel)]='selectedCategory' (ngModelChange)='onCategoryChange($event)'>
<option *ngFor='let category of categories' [ngValue]='category.id'>{{category.name}}</option>
</select>
</div>
<div class='sorted-list__body'>
<div *ngFor="let item of data | orderBy: selectedCategory.id ">
<ng-content></ng-content>
</div>
</div>
</div>
以上不起作用,这里缺少什么?我想我需要使用
ng-template
在这里但不确定它应该如何嵌入在这里?
最佳答案
我找到了 this解决方案并针对 Angular 5 和您的特定组件对其进行了修改。如 ngOutletContext
是 removed来自 Angular 第 5 版 here是 stackblitz 中的一个例子。
SortedList 组件模板
<div *ngFor="let item of items">
<template [ngTemplateOutletContext]='{item: item}' [ngTemplateOutlet]="templateVariable"></template>
</div>
SortedList 组件 ts
@Input() items: any[];
@ContentChild(TemplateRef) templateVariable: TemplateRef<any>;
应用组件模板
<app-sorted-list [items]="myItems">
<ng-template let-item="item">
<!--Here can be any component-->
<app-sorted-list-item [item]="item"></app-sorted-list-item>
</ng-template>
</app-sorted-list>
关于angular - Angular 中可重用的自定义组件列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50450929/