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

Angular5提交表单时如何仅重置部分FormControl输入框而非全部

Angular 5 表单部分重置实现方案

Angular 响应式表单的reset()方法支持自定义重置值,也支持单独操作指定控件,以下是两种常用实现方式:

方案1:单独重置指定控件

适合需要重置的字段数量较少的场景,直接获取对应控件调用reset()方法即可:

// 表单提交成功后执行的逻辑
onSubmit() {
  // 示例:重置contactForm下的 lastName、name、email、mobile、cmd 字段,保留client和Form.pro的原有值
  this.sForm.get('contactForm.lastName').reset('');
  this.sForm.get('contactForm.name').reset('');
  this.sForm.get('contactForm.email').reset('');
  this.sForm.get('contactForm.mobile').reset('');
  this.sForm.get('contactForm.cmd').reset('');

  // 如需重置Form下的pro字段,新增以下代码即可
  // this.sForm.get('Form.pro').reset('');

  // 可选:重置表单的触摸、提交状态
  this.sForm.markAsPristine();
  this.sForm.markAsUntouched();
}

方案2:批量重置保留指定字段

适合需要重置的字段数量较多的场景,先取出要保留的字段值,再调用整个表单的reset()方法传入配置:

onSubmit() {
  // 取出需要保留的字段当前值
  const savedClient = this.sForm.get('contactForm.client').value;
  const savedPro = this.sForm.get('Form.pro').value;

  // 批量重置,指定保留字段的取值,其余字段默认清空为初始值
  this.sForm.reset({
    Form: {
      pro: savedPro // 需清空pro则赋值为''即可
    },
    contactForm: {
      client: savedClient, // 保留client当前值
      lastName: '',
      name: '',
      email: '',
      mobile: '',
      cmd: ''
    }
  });
}

注意事项

如果调用reset()时没有给对应字段传值,该字段会被重置为初始化时的默认值,而非当前值。例如你代码中client字段初始化默认值为this.client,如果重置时没有给client传当前值,该字段会回到初始化时的this.client取值。

内容的提问来源于stack exchange,提问作者maro zoldik

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 06:45:01