如何根据属性以角度输出带有 *ngFor 的组?

Rol*_*ndo 5 angular

假设我有以下对象“myarr”:

[
    {'name':'Mary', 'chapter':'Chapter 1'},
    {'name':'Joseph', 'chapter':'Chapter 1'},
    {'name':'John', 'chapter':'Chapter 2'},
    {'name':'Carl', 'chapter':'Chapter 3'},
    {'name':'Jacob', 'chapter':'Chapter 3'}
]
Run Code Online (Sandbox Code Playgroud)

是否可以使我可以输出以下内容:

第1章

玛丽

约瑟夫

第2章

约翰

第3章

卡尔

雅各布

如果是这样,仅用一个列表来完成此任务的好方法是什么?我不想硬编码第 1 章、第 2 章、第 3 章。我想从数据中推断。

[
    {'name':'Mary', 'chapter':'Chapter 1'},
    {'name':'Joseph', 'chapter':'Chapter 1'},
    {'name':'John', 'chapter':'Chapter 2'},
    {'name':'Carl', 'chapter':'Chapter 3'},
    {'name':'Jacob', 'chapter':'Chapter 3'}
]
Run Code Online (Sandbox Code Playgroud)

Vit*_*vzh 11

您可以通过一种“肮脏”的技巧来实现这一目标。我个人建议您对项目进行分组,但如果您想坚持使用单个列表,这里是 100% 有效的解决方案。

步骤是:

  1. 按章节对数组进行排序
  2. 渲染标题时依赖于前一项的不同章节

打字稿

export class AppComponent  {
  arr = [
    {'name':'Mary', 'chapter':'Chapter 1'},
    {'name':'Joseph', 'chapter':'Chapter 1'},
    {'name':'John', 'chapter':'Chapter 2'},
    {'name':'Carl', 'chapter':'Chapter 3'},
    {'name':'Jacob', 'chapter':'Chapter 3'}
  ];

  constructor() {
    this.arr = this.arr.sort((a,b) => a.chapter > b.chapter ? 1 : -1);
  }
}
Run Code Online (Sandbox Code Playgroud)

超文本标记语言

<div *ngFor="let item of arr; let index = index">
  <h3 *ngIf="!arr[index-1] || item.chapter !== arr[index-1].chapter">{{item.chapter}}</h3>
  {{item.name}}
</div>
Run Code Online (Sandbox Code Playgroud)

StackBlitz:https://stackblitz.com/edit/angular-4y6anf


Nad*_*lta 1

在这里检查这个例子: https: //stackblitz.com/edit/group-by-inangular

您需要首先按章节对项目进行分组,这应该在您的 ts 文件中完成,如下所示:

groupArr = this.myarr.reduce((r,{group})=>{
        if(!r.some(o=>o.chapter==chapter)){
          r.push({chapter,groupItem:this.myarr.filter(v=>v.chapter==chapter)});
    }
    return r;
    },[]);
Run Code Online (Sandbox Code Playgroud)

然后在你的 html 中执行以下操作:

   <table>
     <tr>
         <th>ID</th>
         <th>Name</th>
      </tr>
        <tbody *ngFor="let item of groupArr">
           <ng-container>
             <tr>
                <td colspan="2"><b>{{item.group}}</b></td>
             </tr>
             <tr *ngFor="let value of item.groupItem">
               <td>{{value.name}}</td>
             </tr>
           </ng-container>
         </tbody>
   </table>
Run Code Online (Sandbox Code Playgroud)