You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular通过双向绑定实现多输入字段实时求和更新总租金的方法

实现方案

第一步:调整TS代码

通过给表单类加计算属性的方式自动求和,不用额外写事件监听逻辑,同时做了空值兼容,字段为空时默认取0,不会出现NaN异常。

class DealPLSFormFields {
  dealName:string;
  dealSummary:string;
  dealPartner:string;
  startDate: string;
  endDate: string;
  rent: number;
  cam:number;
  totalBrokerCommission: number;
  supportServicesFee: number;
  // 补全缺失的字段类型
  estimatedOtherRevenue: number;
  descriptionOfOtherRevenue: string;
  buildOutCostReimbursement: number;
  dealId: number;
  securityMonitoring: number;

  constructor(){
    this.dealName = null;
    this.dealSummary = null;
  }

  // 新增自动求和的计算属性
  get totalMonthlyRentAndFees(): number {
    return (this.rent || 0) 
      + (this.cam || 0) 
      + (this.securityMonitoring || 0) 
      + (this.supportServicesFee || 0) 
      + (this.estimatedOtherRevenue || 0);
  }

  // 如果需要支持手动修改总金额,可以保留下面的setter,不需要直接删掉即可
  set totalMonthlyRentAndFees(val: number) {
    // 自定义赋值逻辑写在这里
  }
}

dealPLSFormFields: DealPLSFormFields;
ngOnInit(): void {
  this.dealPLSFormFields = new DealPLSFormFields();
}

第二步:调整HTML代码

总金额是计算生成的,建议设为只读,避免用户手动输入覆盖计算结果,也可以根据需求去掉只读属性。

<div fxLayout="row" fxLayoutAlign="space-between center" >
  <mat-form-field appearance="fill" class="w-49per">
    <mat-label>月租金</mat-label>
    <input matInput [(ngModel)]="dealPLSFormFields.rent" [required]="isExistingDeal">
  </mat-form-field>
  <mat-form-field appearance="fill" class="w-49per">
    <mat-label>月公共区域维护费(CAM)</mat-label>
    <input matInput [(ngModel)]="dealPLSFormFields.cam" [required]="isExistingDeal">
  </mat-form-field>
</div>
<div fxLayout="row" fxLayoutAlign="space-between center" >
  <mat-form-field appearance="fill" class="w-49per">
    <mat-label>月安保监控费</mat-label>
    <input matInput [(ngModel)]="dealPLSFormFields.securityMonitoring" [required]="isExistingDeal">
  </mat-form-field>
  <mat-form-field appearance="fill" class="w-49per">
    <mat-label>月支持服务费</mat-label>
    <input matInput [(ngModel)]="dealPLSFormFields.supportServicesFee" [required]="isExistingDeal">
  </mat-form-field>
</div>
<mat-form-field appearance="fill">
  <mat-label>预估其他收入(如比例租金、推荐费等)</mat-label>
  <input matInput [(ngModel)]="dealPLSFormFields.estimatedOtherRevenue" [required]="isExistingDeal">
</mat-form-field>
<mat-form-field appearance="fill">
  <mat-label>其他收入描述</mat-label>
  <input matInput [(ngModel)]="dealPLSFormFields.descriptionOfOtherRevenue" [required]="isExistingDeal">
</mat-form-field>
<mat-form-field appearance="fill">
  <mat-label>月租及相关费用总计</mat-label>
  <input matInput [value]="dealPLSFormFields.totalMonthlyRentAndFees" [required]="isExistingDeal" readonly>
</mat-form-field>

调整完成后,任意输入字段的值修改时,总金额会自动同步更新,完全符合需求。

内容的提问来源于stack exchange,提问作者Ananya Amar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 01:48:03