Angular 2添加输入值

时间:2017-07-10 19:42:01

标签: html angular typescript

如何添加在输入中输入的值

这是我的HTML, 但我不知道我是否应该在ts中写点什么

<div class="small-7 columns">
  <md-input-container>
    <input type="number" id="fnum" placeholder="fnum">
  </md-input-container>
  <md-input-container>
    <input type="number" id="snum" placeholder="snum">
  </md-input-container>
  <md-input-container>
    <input disabled>{{ (snum) + (fnum) }}
  </md-input-container>
</div>

如果你能帮助我,我将不胜感激

1 个答案:

答案 0 :(得分:1)

您可以使用ngModel获取input值,使用ngModelChange进行更改检测。然后,将它们添加到ts中,并更新包含添加项的第三个变量。

HTML:

<md-input-container>
    <input mdInput type="number" id="fnum" placeholder="fnum" 
           [(ngModel)]="fnum" (ngModelChange)="addNums()">
</md-input-container>

<p></p>

<md-input-container>
    <input mdInput type="number" id="snum" placeholder="snum" 
           [(ngModel)]="snum" (ngModelChange)="addNums()">
</md-input-container>

<p></p>  

<md-input-container>
    <input mdInput disabled>{{ total }}
</md-input-container>

在ts:

fnum: number = 0;
snum: number = 0;

total: number = 0;

addNums(){
  this.total = this.fnum + this.snum;
}

demo