Home > Software design >  calculate grand total of items in *ngFor in ionic
calculate grand total of items in *ngFor in ionic

Time:09-05

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 >
    <ion-col size="5" >
      Name
    </ion-col>
    <ion-col size="2" >
      Price
    </ion-col>
    <ion-col size="3" >
      Amount
    </ion-col>
    <ion-col size="3" >
      Total
    </ion-col>
  </ion-row>

  <ion-row nowrap  *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 >
    <ion-col size="5"   >
      <!-- Name -->
    </ion-col>
    <ion-col size="2"  >
      <!-- price -->
    </ion-col>
    <ion-col size="3" >
      grand amount total
    </ion-col>
    <ion-col size="3" >
      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

CodePudding user response:

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" >
      grand amount total
    </ion-col>
    <ion-col size="3" >
      {{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;
  }
  • Related