Search code examples
angularangular-forms

Angular forms - compute 2 input and display value with just update onchange


I want to input two values in input element and compute them but not with submit button, but using change event. How to do this?

example html

<form>
    <div class="form-group">
      <label>Input 1</label>
      <input type="number" class="form-control" name="input">
    </div>
    <div class="form-group">
      <label>Input 2</label>
      <input type="number" class="form-control" name="reference">
    </div>
    <div class="form-group">
      <label>Sum</label>
      <input type="text" class="form-control" name="difference">
    </div>
</form>

It should be like this, when i type input 1 = 2 & input 2 = 3, automatically add the two inputs and result like to this sum = 5


Solution

  • The change event on your inputs will call the summing function you are looking to execute.

    To be explicit, insert (change)=“sum()“ in your input tag and then define your sum function in your component.ts, like so:

    component.html

    <form>
        <div class="form-group">
          <label>Input 1</label>
          <input type="number" class="form-control" name="input1" (change)="sum()" [(ngModel)]="input1">
        </div>
        <div class="form-group">
          <label>Input 2</label>
          <input type="number" class="form-control" name="input2" (change)="sum()" [(ngModel)]="input2">
        </div>
        <div class="form-group">
          <label>Sum</label>
          <p>{{total}}</p>
        </div>
    </form>
    

    component.ts

    @Component({
      selector: 'app-selector',
      templateUrl: './name.component.html',
      styleUrls: ['./name.component.css']
    })
    export class NameOfComponent {
      total: number
      input1: number = 0
      input2: number = 0
    
      sum () {
        this.total = this.input1 + this.input2
      }
    }