![](/img/trans.png)
[英]how to build JSON data using ngModel in form and table with ngFor in Angular?
[英]Angular: linking data to dynamic table using *ngFor
我正在创建一个动态表。 下面我的 json 结构的问题是 Student 对象在对象中不包含 Subjects 数组,而是通过 Links[] 定义 Student[] 和 Subjects[],其中为学生定义了一个主题的链接。
您对如何在 中创建 *ngFor 有什么建议吗? 将每个学生与其学科联系起来的区域?
json 结构如下所示:
export class StudentsAndSubjects {
info: SchoolInformation;
}
export class SchoolInformation {
students: Students[];
subjects: Subjects[];
links: Links[];
}
export class Students {
id: string; //example: student_1
name: string;
surname: string;
};
export class Subjects{
id: string; //example: subject_1
name: string;
};
export class Links{
studentId: string; //example: student_1
subjectId: string; //example: subject_1
};
表结构:
@Component({
selector: 'app-student-and-subjects',
template: `
<table>
<tr *ngFor="let row of rowHeaders">
<td *ngFor="let item of data.info.students.name">
<span *ngIf="row !== 'Subjects'">{{ item[row] }}</span>
</td>
<table *ngIf="row === 'Subjects'">
<tr **???**>
<td>{{ subject}}</td>
</tr>
</table>
</tr>
</table>
`;
})
export class StudentsAndSubjects {
@Input() data: StudentSubjectData;
readonly rowHeaders = ['Student','Subjects']
}
首先,我认为您需要稍微调整一下您的表格。 由于科目表与特定学生相关联,因此它可能应该位于包含该学生数据的td
中:
<table>
<tr *ngFor="let row of rowHeaders">
<td *ngFor="let student of data.info.students"> <--- each td contains data for a student
<span *ngIf="row !== 'Subjects'">{{ student.name }}</span>
<table *ngIf="row === 'Subjects'"> <--- move this table inside the td
<tr>
<td *ngFor="let subject of getSubjectsForStudent(student)"> <-- the *ngFor you were missing
{{ subject.name }}
</td>
</tr>
</table>
</td>
</tr>
</table>
另请注意,我更改了您的*ngFor="let item of data.info.students.name"
所以它迭代data.info.students
而不是data.info.students.name
因为您需要学生实例数据(和 data.info ) data.info.students.name
不是一个集合)。
为了显示学生姓名,我将{{ item[row] }}
替换为{{ student.name }}
。
然后,要显示该学生的科目,您需要创建一个接受学生对象(或只是其id
)的方法,然后解析数据并返回学生的相关科目。
该方法是您在询问的缺少的*ngFor
中需要的方法。
(当然,您也可以提前将数据转换为映射对象,将学生映射到他们的科目。)
因此,您要询问的丢失的*ngFor
看起来像这样:
<td *ngFor="let subject of getSubjectsForStudent(student)">
请注意,它在td
上,而不是在标记中的tr
上。 这是因为每个科目都有自己的单元格,而不是自己的行——所有科目都在同一行。
这是一个 StackBlitz展示了这种方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.