MewTwo
MewTwo

Reputation: 15

Angular 2+ Multi Calculate & Multi Result

I am trying to get my first Angular app up and running, and running into some errors.

I am getting the error:

TS2304: Cannot find name 'result__i' and TS2551: Property 'second__i' does not exist on type 'AppComponent'.

I expect the output:

result0:10
result1:14

But not working.

HTML Code:

<input type="number" [(ngModel)]="first">
<input type="number" [(ngModel)]="second_0">
<input type="number" [(ngModel)]="second_1">

<br>result0:{{result_0}}
<br>result1:{{result_1}} 

<br><br>
<input type="submit" value="Submit" (click)="sum()">

app.component.ts:

export class AppComponent {
  first = 6;
  second_0 = 4;
  second_1 = 8;

public sum() {
  for (let _i = 0; _i < 2; _i++) {
      result__i = this.first + this.second__i;
  }
  return false;
  }
}

Upvotes: 1

Views: 68

Answers (3)

Prashant Pimpale
Prashant Pimpale

Reputation: 10697

I would do something like this, a bit in a Dynamic way so in case of an item increased in the secondNos list then no need to change in HTML Code

Reformed HTML Code:

<input type="number" [(ngModel)]="first">

<span *ngFor="let obj of secondNos">
        <input type="number" [(ngModel)]="obj">
</span>
<span *ngFor="let obj of result; let i=index">
        <br>result {{i}} : {{obj}}
</span>
<br>
<br>
<input type="submit" value="Submit" (click)="sum()">

In TS:

export class AppComponent {
  first = 6;
  secondNos = [4, 8, 123]; // Incase of new items in the list no need to change in HTML Code
  result = [];

  public sum() {
    this.secondNos.forEach(x => {
      var addition = this.first + x;
      this.result.push(addition)
    })
  }
}

Upvotes: 0

alarcl
alarcl

Reputation: 372

template:

<input type="number" [(ngModel)]="first">
<input type="number" [(ngModel)]="second[0]">
<input type="number" [(ngModel)]="second[1]">

<br>result0:{{result[0]}}
<br>result1:{{result[1]}} 

<br><br>
<input type="submit" value="Submit" (click)="sum()">

in component:

first = 6;
second = [4, 8];
result = []

public sum() {
    for (let _i = 0; _i < 2; _i++) {
        this.result[_i] = this.first + this.second[_i];
    }
}

planker

Upvotes: 1

Yoarthur
Yoarthur

Reputation: 917

In your component set this.

export class AppComponent {
  first = 6;
  second_0 = 4;
  second_1 = 8;


public sum() {

  let result__i = 0
  let second__i = 0

  for (let _i = 0; _i < 2; _i++) {

      return result__i = this.first + second__i;

  }
  }
}

The compiler is complaining about such property result__i and second__i are not defined

Upvotes: 0

Related Questions