[英]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.