简体   繁体   中英

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.

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. It was much easier to evaluate a numeric expression with Angular1 but I can't find any example of this with 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
  • keep ngModel value untouched by this fixed value...

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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