我正在使用Angular 6和HTML。我想求和或求和一个嵌套数组字段并在行中显示。
我有一个包含多个学生的数组列表('marksEntryList'),也有一个包含多个课程的嵌套数组列表('marksDistributionList')。我放置了单独的课程标记,所有课程标记将连续显示。
marksEntryList: any = [
{
studentId: '101',
studentName: "Monir Zaman",
marksDistributionList: [
{
courseId: '01',
courseTitle: "Math",
obtainedMarks: null
},
{
courseId: '02',
courseTitle: "English",
obtainedMarks: null
},
{
courseId: '03',
courseTitle: "Physics",
obtainedMarks: null
}
]
},
{
studentId: '102',
studentName: 'Michel Jordan',
marksDistributionList: [
{
courseId: '01',
courseTitle: "Math",
obtainedMarks: null
},
{
courseId: '02',
courseTitle: "English",
obtainedMarks: null
},
{
courseId: '03',
courseTitle: "Physics",
obtainedMarks: null
}
]
}
]
<table border="1">
<thead>
<tr>
<th>ID</th> <th>Name</th><th>Admission Test Subjects</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let applicant of marksEntryList">
<td>{{applicant.studentId}}</td>
<td>{{applicant.studentName}}</td>
<td>
<table>
<th *ngFor="let testMarks of applicant.marksDistributionList">
{{testMarks.courseTitle}}
</th>
<tbody>
<tr>
<td *ngFor="let testMarks of
applicant.marksDistributionList">
<input type="text" [(ngModel)]="testMarks.obtainedMarks" />
</td>
<span>Total : 0</span>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
我希望对单行的所有课程分数进行总计或求和,并将其显示在总计标签中。谢谢。
在组件中创建方法getTotal()
,并从模板调用此方法。
组分:
getTotal(marks) {
let total = 0;
marks.forEach((item) => {
total += Number(item.obtainedMarks);
});
return total;
}
模板:
<span>Total: {{ getTotal(applicant.marksDistributionList) }}</span>
StackBlitz上的实时演示:https://stackblitz.com/edit/angular-sum-table-ngmodel-dsfkpf