Home > Mobile >  For loop not printing the input value on first index in angular
For loop not printing the input value on first index in angular

Time:09-26

hi am developing a rent calculator app in angular which take three inputs: rent, amount of rent increase per year; and number of years to calculate rent for. which have one issue that for loop is not printing the entered value of rent on first index it prints the first calculated value on first index,i want to print the entered value on first index

html

<div >

<h1>Rent Calculator</h1>

<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)]="years">

<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: any;

  years: any;

  rent: any;

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


  nextYearCalculatedRent: any;


  calculate() {

    for (let i = 0; i < this.years; i  ) {

      let rentValue = this.nextYearCalculatedRent || this.rent;

      this.nextYearCalculatedRent = rentValue   (rentValue * this.increase / 100);


      this.total[i] = (Math.round((this.nextYearCalculatedRent   Number.EPSILON) * 100) / 100); 
//here store in the array the result

    }
  }
}

CodePudding user response:

You have to add a year to your array before the loop.

Also, your code is not stable (try calculating for 20 years, then change it to 2 years, see what happens).

Here is an updated piece of code for you.

  constructor() {}

  increase: any;

  years: any;

  rent: any;

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

  nextYearCalculatedRent: any;

  calculate() {
    this.total = [];

    let previousRent = this.rent;
    this.total.push(previousRent);
    for (let i = 0; i < this.years; i  ) {
      const rent = previousRent * (1   this.increase / 100);
      previousRent = rent;
      this.total.push(Math.floor(rent));
    }
  }
  • Related