Angular 11中用ngFor遍历indexNumArr作为row.quiz_records下标功能失效
问题根因
- 插值语法错误:Angular 插值表达式
{{ }}内部不能嵌套使用另一层{{ }},直接写变量即可,原代码中row.quiz_records[{{index}}]的写法不符合语法规范。 - 列标识重复:Angular Material mat-table 要求所有
matColumnDef属性值必须唯一,你在循环中重复使用question_text、user_answers作为列标识,会导致列渲染冲突。 - 缺失必填配置:原代码没有声明表头、行渲染指令,也没有配置
displayedColumns数组指定需要渲染的列,mat-table 无法正常渲染动态生成的列。
修正后代码
TS 代码
import { Component, OnInit } from '@angular/core'; @Component({ // 保留你原有组件配置 }) export class YourComponent implements OnInit { indexNumArr: number [] = [0, 1]; // 存储动态生成的唯一列名 displayedColumns: string[] = []; // 保留你原有的数据源定义 dataSourceQuizOverview = []; ngOnInit() { // 生成唯一列名 this.indexNumArr.forEach(index => { this.displayedColumns.push(`question_text_${index}`, `user_answers_${index}`); }); // 保留你原有给dataSourceQuizOverview赋值的逻辑,注意取接口返回的quizRemarks字段 } }
HTML 代码
<table mat-table [dataSource]="dataSourceQuizOverview" matSort> <ng-container *ngFor="let index of indexNumArr"> <!-- 动态拼接唯一列标识 --> <ng-container [matColumnDef]="'question_text_' + index"> <th class="font" mat-header-cell *matHeaderCellDef mat-sort-header>问题{{index + 1}}</th> <td class="font" mat-cell *matCellDef="let row">{{row.quiz_records[index]?.question_text}}</td> </ng-container> <ng-container [matColumnDef]="'user_answers_' + index"> <th class="font" mat-header-cell *matHeaderCellDef mat-sort-header>答案{{index + 1}}</th> <td class="font" mat-cell *matCellDef="let row">{{row.quiz_records[index]?.user_answers}}</td> </ng-container> </ng-container> <!-- 补充表头、行渲染配置 --> <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr> <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr> </table>
优化说明
代码中使用?.可选链运算符,避免quiz_records对应下标无数据时抛出 undefined 报错。
内容的提问来源于stack exchange,提问作者reginald bollosa
相关产品推荐
相关产品推荐

