角度形式-只需更新onchange

时间:2018-07-19 00:10:05

标签: angular angular-forms

我想在输入元素中输入两个值并计算它们,但是不使用Submit按钮,而是使用change事件。 如何执行此操作?

示例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>

应该是这样的,当我输入input 1 = 2input 2 = 3时,会自动将这两个输入和结果相加为此sum = 5

2 个答案:

答案 0 :(得分:0)

输入中的change事件将调用您要执行的求和函数。

为明确起见,在(change)=“sum()“标记中插入input,然后在sum中定义component.ts函数,如下所示:

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
  }
}

答案 1 :(得分:0)

您不需要使用(change)=“ sum()”。您只需编写{{input1 + input2}}

<form>
      <input type="number" class="form-control" name="input1"  [(ngModel)]="input1">
      <input type="number" class="form-control" name="input2"  [(ngModel)]="input2">
      <p>{{input1+input2}}</p>
</form>