For loop only printing first iteration multiple time

Viewed 38

I am building a rent calculator app which have 3 fields total rent,rent incresese per year and number of years to calculate rent for .when i fill the input field the code only print first iteration multiple time i want it to print increased value with years

Html file

Rent Calculator

<input type="number" name="rent" placeholder="Enter your total rent" [(ngModel)]="rent" />

<input type="number" placeholder="Rent increase per Year" [(ngModel)]="increase">

<input type="number" placeholder="Number of Total Years" [(ngModel)]="months">

<button type="button" (click)="calculate()"> Calculate </button>
<br>

<h4 *ngFor="let r of total;let i=index">

    Year {{i+1}}&nbsp; &nbsp;=&nbsp;&nbsp;{{r}}&nbsp;Rs

</h4>

ts file...

export class RentCalculatorComponent {

  constructor() { }

  increase!: number;

  months!: number;

  rent!: number;

  new!: number;

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

  calculate() {

    for (let i = 0; i <= this.months - 1; i++) {
     
      this.new = this.rent + this.rent * this.increase / 100;

      this.total[i] = this.new.toFixed(2);; //here store in the array the result

      console.log(this.total[i]);

    }
  }
}
1 Answers

You are initializing an array of length 0. When you are looping from 0 to month.length - 1 you are basically setting values out of bounds of your array. You should try to use this.total.push(this.new.toFixed(2)); to increase the length of your array.

Nevertheless a couple of hints:

  • You should not name variables new, since this is a reserved word in many languages
  • you should not use the "bang-operator" (or "non-null-assertion-operator") when the variable is indeed not set. You should just initialize it with a valid value in your case
Related