Angular Form 重置值并设置其所有初始值而不是 null [英] Angular Form reset value and set all its initial value rather than null

查看:40
本文介绍了Angular Form 重置值并设置其所有初始值而不是 null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如我有下面的表格.

searchForm = new FormGroup({
    firstName: new FormControl(''),
    lastName: new FormControl('')
  })

问题是,当我使用 searchForm.reset() 时,初始值设置为 null 而不是空字符串 ''我在 FormControl 中设置为初始值.

The problem is that when I use searchForm.reset() the initial value is set to null and not to empty string '' that I set as an initial value in the FormControl.

我已经尝试执行下面的代码并且它有效.问题是,例如我有 20 个 FormControl,我需要输入所有内容并在 .reset({firstName:'', other20properties..}) 中初始化它

I have tried doing the code below and it works. The problem is that for example I have like 20 FormControl, I will need to type it all and initialize it in .reset({firstName:'', other20properties..})

this.searchForm.reset(
      {
        firstName: '',
        lastName: ''
      }
    );

有没有办法重置表单并将其所有初始值设置为空字符串''.

Is there a way to reset the form and set all its initial value to empty string ''.

推荐答案

在这些类型的场景中,最好将表单初始化包装到一个单独的方法中,并在 form.reset 之后像这样调用该方法 -

In these type of scenarios better to wrap your form initialization into a separate method and call that method after form.reset like this -

formInit() {
 searchForm = new FormGroup({
    firstName: new FormControl(''),
    lastName: new FormControl('')
 })
}


anotherFunction() {
  this.searchForm.reset();
  this.formInit();
}

这篇关于Angular Form 重置值并设置其所有初始值而不是 null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆