Not getting every value of for loop in angular

Viewed 38

In angular for loop is printing all values in console, but printing only the last value on the web page. I want to show all values on the web page.

export class RentCalculatorComponent {
    constructor() { }

    rent: any = '';

    increase: any = '';

    months: any = '';

    calculate() {
      for (let i = 1; i <= this.months; i++) {
        this.rent = this.rent + this.rent * this.increase / 100
        console.log(this.rent);
      }
}
1 Answers

In Angular, when you call to a function, the function is executed and, after, repaint the app. it's the reason because after execute the loop, your variable "rent" has the last value and is this value who is showed in the app.

If you want to show all the values, you need use an array and show the array

rent: any[] = []; //declare an array

calculate() {
      let rent=0; //use a auxiliar variable
      for (let i = 1; i <= this.months; i++) {
        rent = rent + rent * this.increase / 100;
        this.rent[i] = rent; //here store in the array the result
                             //see that use this.rent[i]
                             //to change the value of the variable "rent"
                             //of the component
        console.log(this.rent[i]);
      }
}

And you show using *ngFor

<div *ngFor="let r of rent;let i=index">
   month {{i+1}} --> {{r}}
</div>

To know about arrays in typescript or arrays in javascript, to know about ngFor

Related