[FIXED] calculate grand total of items in *ngFor in ionic

Issue

I’m new to ionic and angular. By fetching data from my SQLite DB I’m displaying list of items using *ngFor and I’m able to show the name, amount, price and total of each item in the list, now the issue is how to get the grand total at the bottom of the list example picture.

here is my .html code

 <ion-grid>
  <ion-row nowrap class="headers">
    <ion-col size="5" class="single-border">
      Name
    </ion-col>
    <ion-col size="2" class="single-border">
      Price
    </ion-col>
    <ion-col size="3" class="single-border">
      Amount
    </ion-col>
    <ion-col size="3" class="single-border">
      Total
    </ion-col>
  </ion-row>

  <ion-row nowrap class="content" *ngFor="let prod of products | async">
    <ion-col size="5"> {{ prod.name }} </ion-col>
    <ion-col size="2"> {{ prod.price }} </ion-col>
    <ion-col size="3"> {{ prod.amount }} </ion-col>
    <ion-col size="3"> {{ prod.total }} </ion-col>
  </ion-row >
  <ion-row  nowrap class="headers">
    <ion-col size="5" class="top-border"  >
      <!-- Name -->
    </ion-col>
    <ion-col size="2"  class="top-border">
      <!-- price -->
    </ion-col>
    <ion-col size="3" class="top-border">
      grand amount total
    </ion-col>
    <ion-col size="3" class="top-border">
      grand total 
    </ion-col>
  </ion-row>
</ion-grid>

the .ts file

 export class ReportPage implements OnInit {

products: Observable<any[]>;

product = {};

constructor(public db: DatabaseService) {}

 ngOnInit() {
  this.db.getDatabaseState().subscribe((rdy) => 
{
  if (rdy) {
    this.db.getDevs().subscribe((devs) => {
      this.developers = devs;
    });
    this.products = this.db.getProducts();
    this.db.normalProducts();
    this.db.repoProduct;
     }
   });
}

async showRepo(item_date: Date) {
  this.db.repoProduct(item_date).then((_) => {
    console.log(_);
    this.product = {};
  });
}

and here is the database

CREATE TABLE IF NOT EXISTS product(id INTEGER PRIMARY KEY AUTOINCREMENT,name TEXT, creatorId INTEGER, price INTEGER, amount INTEGER, total INTEGER NOT NULL);

Thanks in advance

Solution

Simply call the method from HTML, you should look into this stackblitz demo to understand how we are getting data from the observable array and also go through the concept of observables and subjects in angular.

in .html file

 <ion-col size="3" class="top-border">
      grand amount total
    </ion-col>
    <ion-col size="3" class="top-border">
      {{callingfunctionhere()}}
    </ion-col>

in .ts file

    callingfunctionhere() {
    let totalall = 0;
    // we need to subscribe to products because it is observable, then 
    //only we will get data
    this.products.subscribe((data) => {
      totalall = data.reduce((sum, current) => sum + current.total, 0);
    });
    return totalall;
  }

Answered By – Exception

Answer Checked By – Senaida (Easybugfix Volunteer)

Leave a Reply

(*) Required, Your email will not be published