'Angular iterate only display one output

I try iterate array value.. When I try to console.log my array, it produce values that I want .. but when I display the data, only one of the value of data got display. Here is my function

getEarning() {
    for (let booking of this.bookings) {
      if (booking.status == 'paid') {
        this.earn = booking.price * 0.6;
        console.log(this.earn);
      }
    }
  }

here how I display the data <p><span class="label">Earning: </span>RM {{earn}}</p>

here is my console log result enter image description here

and here the result of my display data enter image description here



Solution 1:[1]

The problem is that you are looping through this.bookings and setting a new value to this.earn and console logging it in that point in time. So you only display the latest value of this.earn in your html file. There are several ways to solve this. The simplest way would be to calculate the earnings directly in your html. Thus, you don't need getEarning() in your ts file.

<div *ngFor="let booking of bookings">
  ...
  <div class="label">Earning: {{booking * 0.6 | number: '1.2-2'}}</div>
</div>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1