可重用的自定义组件列表在Angular中

4

我希望在Angular5中创建可重用的SortedList组件。该列表应接受任何listItems(对象)数组作为属性。从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,但不确定应该如何嵌入它?

1个回答

3
我找到了这个解决方案,并针对 Angular 5 和您特定的组件进行了修改。由于 ngOutletContext 已经在 Angular 5 的版本中被删除,所以这里提供了在 stackblitz 中的示例。 SortedList 组件模板
<div *ngFor="let item of items">
    <template [ngTemplateOutletContext]='{item: item}' [ngTemplateOutlet]="templateVariable"></template>
</div>

排序列表组件 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>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接