How to sum nested array field in table row in angular 6?

Issue

I am using Angular 6 and Html. I want to sum or total a nested array field and show in row.

I have a array list (‘marksEntryList’) with multiple student and also have a nested array list (‘marksDistributionList’) with multiple courses. I put individual course marks and all courses marks will show in total in a row.

I want like this image:enter image description here

stackblitz

ts file

    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
          }
        ]
       }
     ]

html

    <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>

I expect to total or sum all courses marks of a single row and show it in to total label. Thanks.

Solution

Create a method getTotal() in component and call this method from template.

Component:

getTotal(marks) {
  let total = 0;

  marks.forEach((item) => {
    total += Number(item.obtainedMarks);
  });

  return total;
}

Template:

<span>Total: {{ getTotal(applicant.marksDistributionList) }}</span>

Live demo on StackBlitz: https://stackblitz.com/edit/angular-sum-table-ngmodel-dsfkpf

Answered By – Nikhil

Answer Checked By – Marie Seifert (AngularFixing Admin)

Leave a Reply

Your email address will not be published.