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

Angular不使用FormGroup如何判断ngModel绑定的表单字段是否有值或已修改?

实现方案

因为你没有使用Angular响应式表单的FormGroup,要判断ngModel绑定字段的dirty状态和值是否存在,可以选以下两种方案实现:

方案1:利用NgModel内置的dirty状态(推荐)

Angular的ngModel指令本身就内置了dirty、valid等表单状态,直接调用即可:

第一步:修改模板代码,给每个输入框绑定ngModel引用

给所有要检查的input/textarea加上模板变量,指向当前的NgModel实例:

<!-- 示例仅展示修改部分,其余属性保留原有逻辑 -->
<mat-form-field appearance="fill">
  <mat-label>Deal Name</mat-label>
  <input 
    matInput
    [(ngModel)]="dealDispositionFormFields.dealName"
    #dealName="ngModel"
    [required]="isExistingDeal">
</mat-form-field>
<mat-form-field appearance="fill">
  <mat-label>Summary of Deal</mat-label>
  <textarea 
    matInput
    class="resize-none"
    [(ngModel)]="dealDispositionFormFields.summary"
    #summary="ngModel"
    [rows]="5"
    [required]="isExistingDeal">
  </textarea>
</mat-form-field>
<mat-form-field appearance="fill">
  <mat-label>Termination Payment</mat-label>
  <input 
    matInput
    (keyup) = "computeBuyout()"
    mask="separator.0" 
    thousandSeparator=","
    [allowNegativeNumbers]="false"
    [(ngModel)]="dealDispositionFormFields.terminationPayment"
    #terminationPayment="ngModel"
    [required]="isExistingDeal">
    <span matPrefix *ngIf="dealDispositionFormFields.terminationPayment">$</span>
</mat-form-field>
<mat-form-field appearance="fill">
  <mat-label>Effective Date</mat-label>
    <input matInput
      (dateChange)="computeBuyout()"
      [matDatepicker]="effectiveDate" 
      [(ngModel)]="dealDispositionFormFields.effectiveDate"
      #effectiveDateModel="ngModel"
      [required]="isExistingDeal">
    <mat-datepicker-toggle matSuffix [for]="effectiveDate"></mat-datepicker-toggle>
    <mat-datepicker #effectiveDate></mat-datepicker>
</mat-form-field>
<mat-form-field appearance="fill">
  <mat-label>Total Broker Commission</mat-label>
  <input 
    matInput
    (keyup) = "computeBuyout()"         
    mask="separator.0" 
    thousandSeparator=","
    [allowNegativeNumbers]="false"
    [(ngModel)]="dealDispositionFormFields.totalBrokerCommission"
    #totalBrokerCommission="ngModel"
    [required]="isExistingDeal">
    <span matPrefix *ngIf="dealDispositionFormFields.totalBrokerCommission">$</span>
</mat-form-field>

第二步:修改TS代码,获取所有NgModel实例并校验

import { ViewChildren, QueryList } from '@angular/core';
import { NgModel } from '@angular/forms';

export class DealIdleDispositionComponent implements OnInit {
  @ViewChildren('dealName, summary, terminationPayment, effectiveDateModel, totalBrokerCommission')
  formFields: QueryList<NgModel>;

  dealDispositionFormFields: DealDispositionFormFields;
  // 如果你需要判断初始值是否为空,可以提前存初始状态
  initialFormValues: any;

  ngOnInit(): void {   
    this.dealDispositionFormFields = new DealDispositionFormFields();
    // 存初始值用于后续对比,可选
    this.initialFormValues = structuredClone(this.dealDispositionFormFields);
  }

  checkIf5FieldsAreDirty(): boolean {
    // 这里的逻辑可以根据你的需求调整:
    // 示例1:判断是否任意一个字段为dirty 或 有输入值,满足则返回true
    return this.formFields.some(field => {
      const hasValue = field.value !== null && field.value !== undefined && field.value !== '';
      return field.dirty || hasValue;
    });

    // 示例2:如果需要判断5个字段全部满足(有值或已修改),把some改成every即可
    // return this.formFields.every(field => {
    //   const hasValue = field.value !== null && field.value !== undefined && field.value !== '';
    //   return field.dirty || hasValue;
    // });
  }
}

你可以在需要展示提示的位置直接调用checkIf5FieldsAreDirty()方法,返回true就展示提示即可。

方案2:自定义对比初始值和当前值判断dirty

如果你不想修改模板代码,可以直接通过对比初始值和当前值判断是否被修改:

export class DealIdleDispositionComponent implements OnInit {
  dealDispositionFormFields: DealDispositionFormFields;
  initialFormValues: DealDispositionFormFields;
  // 要校验的字段列表
  checkFields = ['dealName', 'summary', 'terminationPayment', 'effectiveDate', 'totalBrokerCommission'];

  ngOnInit(): void {   
    this.dealDispositionFormFields = new DealDispositionFormFields();
    // 深拷贝初始值,避免引用类型影响
    this.initialFormValues = structuredClone(this.dealDispositionFormFields);
  }

  checkIf5FieldsAreDirty(): boolean {
    // 示例:任意一个字段有值 或 和初始值不同(即被修改过)返回true
    return this.checkFields.some(fieldKey => {
      const currentVal = this.dealDispositionFormFields[fieldKey];
      const initialVal = this.initialFormValues[fieldKey];
      const hasValue = currentVal !== null && currentVal !== undefined && currentVal !== '';
      const isDirty = currentVal !== initialVal;
      return hasValue || isDirty;
    });
  }
}

注意:如果你的表单有重置逻辑,重置的时候记得同步更新initialFormValues为重置后的值,避免校验逻辑出错。

内容的提问来源于stack exchange,提问作者Jaya Reddy

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 20:45:01