0

我有从后端 API 收到的数据对象,如下所示:

[{"testNumber":1,
   "students":[{"name":"Jane Doe","status":"PASSED"}, 
               {"name":"John Doe","status":"PASSED"}]},
 {"testNumber":2,
   "students":[{"name":"Jane Doe","status":"PASSED"}, 
               {"name":"John Doe","status":"FAILED"}]},
etc...
]

这是我检索名称的代码:

<ng-container matColumnDef="name">
  <th mat-header-cell *matHeaderCellDef > Student Name </th>
  <td mat-cell *matCellDef="let element">
      <span *ngFor="let student of element.students"> {{student.name}} </span>
  </td>
</ng-container>

然而,使用上面的代码,所有的名字都像这样组合到一个单元格中:Jane DoeJohn Doe...

如何将每个名称拆分为一个新行?基本上我想要显示的是这种格式:

| Student Name  | Test 1    | Test 2    | Test 3    | Test N    |
| Student 1     | Pass      | Fail      | Pass      | ...       |
| Student 2     | Pass      | Pass      | Pass      |           |
| Student 3     | Pass      | Pass      |           |           |
| Student 4     | Pass      |           |           |           |

另外,使用 ngFor 并为“测试 1”、“测试 2”等填充单元格数据的最佳方法是什么?

这是我当前在 TypeScript 中的数据模型(请注意,我也控制后端服务,所以如果需要更改数据模型以使前端更容易,我可以更改它):

export class Test {
    testNumber: number;
    students: Student[];
}
export class Student {
    name: string;
    status: string;
}

谢谢!

4

1 回答 1

0

您首先需要将您的集合设置为更接近您正在显示的表格,该表格是具有测试状态的学生列表。由于您的列是动态的,因此您还需要一组测试来表示要在表中显示的列。

const getTests = of([
  {
    "testNumber":1,
    "students":[{"name":"Jane Doe","status":"PASSED"}, 
               {"name":"John Doe","status":"PASSED"}]},
  {
    "testNumber":2,
    "students":[{"name":"Jane Doe","status":"PASSED"}, 
               {"name":"John Doe","status":"FAILED"}]
  }
]);

getTests.subscribe(tests => {
  const studentMap = new Map<string, {}>();
  for(const test of tests) {
    for(const student of test.students) {
      const studentTests = {
        name: student.name,
        ...studentMap.get(student.name),
        [test.testNumber]: student.status
      };
      studentMap.set(student.name, studentTests)
    }
  }

  // columns
  this.testColumns = tests.map(t => t.testNumber);

  // table data: use this as the table data source
  this.students = Array.from(studentMap.values());
});

这将为学生生成一个数组,看起来像

[
  { "name": "Jane Doe", "1": "PASSED", "2": "PASSED" },
  { "name": "John Doe", "1": "PASSED", "2": "FAILED" }
] 

因此,在您的组件中,您可以遍历每个测试编号以创建列:

<ng-container matColumnDef="name">
  <th mat-header-cell *matHeaderCellDef>Student Name</th>
  <td mat-cell *matCellDef="let student">
    {{student.name}}
  </td>
</ng-container>

<ng-container [matColumnDef]="testNumber" *ngFor="let testNumber of testColumns ">
  <th mat-header-cell *matHeaderCellDef>Test {{testNumber}}</th>
  <td mat-cell *matCellDef="let element"> {{ element[testNumber] }} </td>
</ng-container>
于 2020-07-19T17:57:19.673 回答