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

标签 angular list angular2-template children ngfor

我想在 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 和您的特定组件对其进行了修改。如 ngOutletContextremoved来自 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/

相关文章:

angular - 是否可以添加动态类以在 Angular 2 中托管?

java - 将 Java 对象传递给 Angular 以满足特定需求

javascript - 如何将使用 Node js 和 Multer 保存在文件系统上的文件返回到 Angular 前端?

python 列表到 csv 文件,每个项目都在新行中

python - bool 值到一个列表中的列名,dataframe pandas python

javascript - VM1052 :19 Error: (SystemJS) TypeScript transpilation failed

angular - Jasmine 测试,导致 mat-select 发出 selectionChange 事件?

angular - 组件间对象的两种方式数据绑定(bind)

python - lstrip(), rstrip() 用于列表

javascript - Angular2 在等待数据加载时更新 View