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

Angular 14表单开发疑问:移除空值对象及控制添加按钮状态

Angular 14表单:移除末尾空居住项与控制添加按钮状态

1. 提交前移除末尾空居住项

提交表单时,直接过滤掉residences数组中所有city和address均为空的对象即可,无需修改表单结构:

修改form.component.ts中的sendFormData方法:

public sendFormData() {
  // 过滤空的居住项(只要city或address有值就保留)
  const validResidences = this.residencesArray.value.filter(item => 
    item.city.trim() !== '' || item.address.trim() !== ''
  );
  // 构造最终提交的数据
  const submitData = {
    ...this.form.value,
    residences: validResidences
  };
  console.log(submitData);
  // 执行实际提交逻辑(如API调用)
}

这种方式不仅能移除末尾的空项,还能处理用户中途添加但未填写的空项,保证提交数据的整洁。


2. 控制"Add residence"按钮的禁用状态

按钮需要同时满足两个条件才启用:主表单验证通过,且当前最后一个居住项已填写至少一个字段。

步骤1:添加判断最后一项是否为空的getter

在form.component.ts中新增:

get isLastResidenceEmpty(): boolean {
  const lastIndex = this.residencesArray.length - 1;
  const lastResidence = this.residencesArray.controls[lastIndex];
  const cityValue = lastResidence.get('city')?.value?.trim() || '';
  const addressValue = lastResidence.get('address')?.value?.trim() || '';
  return cityValue === '' && addressValue === '';
}

步骤2:修改按钮的禁用绑定

更新form.component.html中的按钮代码:

<button
  (click)="addResidence()"
  mat-raised-button
  color="primary"
  [disabled]="!form.valid || isLastResidenceEmpty"
>
  Add residence
</button>

这样只有当主表单有效,且当前最后一个居住项已填写内容时,才能点击添加新项,避免产生连续的空项。


内容的提问来源于stack exchange,提问作者Razvan Zamfir

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 11:55:40