简体   繁体   English

角度2:使用ngModel求和2个数字

[英]Angular 2: summing 2 numbers with ngModel

I'm trying to sum ngModel variable with another variable and display the result as interpolation but I don't see the result updated dynamically. 我正在尝试将ngModel变量与另一个变量求和,并将结果显示为插值,但我看不到结果动态更新。

Here's my input text field: 这是我的输入文本字段:

<input type="text" [(ngModel)]='downpayment1' class="form-control" placeholder="Option 1 Down Payment (%)">

typescript code looks like this: 打字稿代码如下所示:

  downpayment1 = 0;
  result = this.downpayment1 + 20;

changing downpayment1 input should also change {{result}} but it doesn't happen. 更改预付定金1的输入也应更改{{result}},但不会发生。 It was much easier to evaluate a numeric expression with Angular1 but I can't find any example of this with Angular2. 用Angular1评估一个数字表达式要容易得多,但是我用Angular2找不到任何这样的例子。 What am I doing wrong here? 我在这里做错了什么?

If i understand correctly what you are trying to achieve is: 如果我正确理解您要实现的目标是:

  • display ngModel value summed with some fixed value 显示与一些固定值求和 ngModel值
  • keep ngModel value untouched by this fixed value... 保持ngModel的值不受此固定值的影响...

then that would be my answer 那就是我的答案

@Component({
    selector: 'my-app',
    template: `
    <h1>Summing example</h1>
    <h2>Fixed value {{fixedValue}}</h2>
    <input type="number" [(ngModel)]='downpayment1' class="form-control" placeholder="Option 1 Down Payment (%)">

    <h2>Sum : {{ fixedValue + downpayment1 }}</h2>
    `
})
export class AppComponent {
    public fixedValue: number = 20;
    public downpayment1: number = 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM