Making sum with angular

Asked

Viewed 1,116 times

2

Someone could help me, I’m starting to use Angular now, and I’m having a big confusion at the time of how to study...

Basically, when I click the button it does nothing... it is possible that the error is grotesque, but I am stuck

<input type="text" placeholder="Valor 1"
(input) = 'valor1'

 />
<input type="text" placeholder="Valor 2"
(input) = 'valor2'

 />
<button (click)="calcularSoma(valor1, valor2)" class="btn btn-primary">Calcular</button>
<p>
  {{calcularSoma(valor1, valor2)}}
</p>
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-calculator',
  templateUrl: './calculator.component.html',
  styleUrls: ['./calculator.component.css']
})
export class CalculatorComponent  {

  value1: number;
  value2: number;
  constructor() {

   }

   calcularSoma(value1:  number,  value2: number){
     return this.value1 + this.value2;
   }

}

1 answer

1


Nice that you’re learning, so there’s a lot of syntax errors in your code HTML as in your TS. For you to pick up an input value in a much used way (but she’s not the only one) is with the directive ngModel, this directive makes the call Two way data Binding, that is, basically it transmits the value of HTML to the TS and vice versa. Well as we have already taken the value of the input, now just add in the function calculate and save the value in a total variable and show on the screen, as it is also not very recommended to perform functions directly in HTML:

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {  
  value1;
  value2;
  valorTotal;

  constructor() {}

  calcularSoma(){
     this.valorTotal = Number(this.value1) + Number(this.value2);
  }

}

<input type="text" placeholder="Valor 1" [(ngModel)]="value1">
<input type="text" placeholder="Valor 2" [(ngModel)]="value2">

<button (click)="calcularSoma()" class="btn btn-primary">Calcular</button>
<p>
  {{ valorTotal }} <br>
</p>

The method Number() was used because the value of an input will always be string if type is text, even typing the variable as number, which would concatenate the values instead of adding them.

  • Thank you! It was extreme, I’m not even a little accustomed to these 2 languages operating this way... If you don’t mind me asking? Why Property Binding or Event Binding wasn’t working?

  • 1

    The Event Binding was not working because basically you were not picking up the input value. To work would have to do something like (input)="valor1 = $Event.target.value".

Browser other questions tagged

You are not signed in. Login or sign up in order to post.