多个相关字段有角度2

时间:2017-09-16 12:12:23

标签: angular

我有一个角度2应用程序,我需要(除了其他人),这4个字段:

总金额,折扣,折扣百分比和净额。 公式是:

净金额=总金额 - 折扣

(如果提供折扣百分比,则应计算折扣并在上述公式中使用)。

有没有办法让我可以让这4件事情相互依赖,如果其中一件事根据公式发生变化就会改变?

1 个答案:

答案 0 :(得分:1)

你可以这样写:

import {Component} from "@angular/core";
@Component({
  selector: 'app-root',
  template: `
        Gross: <input type='text'   [(ngModel)]="grossAmount">
        Discount Percent  <input type='text' [(ngModel)]="discountPercent" (change)="calculateNet()">
        Discount:  {{discount}} 
         Net Amount: {{netAmount}}
         `
})
export class AppComponent {
  grossAmount = 0;
  discount = 0;
  discountPercent=0;
  netAmount=0;

 calculateNet(){
   if (this.discountPercent > 0){
     this.discount = this.grossAmount*this.discountPercent/100;
     this.netAmount = this.grossAmount - this.discount;
   }
 }
}