简体   繁体   English

如何将反应式表单控件重置为原始状态?

[英]How can I reset a reactive form control to originate state?

Hi I need help with a reactive forms element.嗨,我需要有关反应式表单元素的帮助。 Basically, it's a required element.基本上,它是必需的元素。 When the view first loads, the element is not red(not showing error that it needs a value).当视图第一次加载时,元素不是红色的(没有显示它需要一个值的错误)。 That is good and it only will show red if I tap inside then navigate away without filling it out.这很好,如果我点击里面然后导航离开而不填写它,它只会显示红色。 The logic I currently have is when I fill it out and submit the form... the form data gets submitted but I remain on the same page but all the previous values are wiped out.我目前的逻辑是,当我填写并提交表单时……表单数据被提交,但我仍然在同一页面上,但所有以前的值都被删除了。 The issue with that is... now the form element thinks I didn't fill it out and is complaining when it should just not complain because technically it's a new form.问题是......现在表单元素认为我没有填写它并且在它不应该抱怨时抱怨,因为从技术上讲它是一个新表格。

Here's my form group:这是我的表单组:

this.transactionForm = fb.group({
      'billNumber': [null, Validators.compose([Validators.required, Validators.pattern('^[a-zA-Z0-9\\-_]*$'), Validators.maxLength(30)])],
      'birthdate': [null, Validators.required],
      'transactionDate': [new Date(), Validators.required],
      'type': ['Sales', Validators.required],
    });

Currently, I have a function called reset() that I call when the form is submitted:目前,我有一个名为 reset() 的函数,我在提交表单时调用它:

reset() {
    this.transactionForm.get('billNumber').setErrors({required: false});
    this.transactionForm.controls['billNumber'].setValue('');
    this.transactionForm.controls['billNumber'].setErrors({'incorrect': false});
    this.transactionForm.controls['billNumber'].markAsUntouched();
    this.transactionForm.controls['billNumber'].markAsPristine();
    this.transactionForm.controls['birthdate'].setValue(null);
    this.transactionForm.controls['birthdate'].markAsUntouched();
    this.transactionForm.controls['birthdate'].markAsPristine();
    this.transactionForm.controls['birthdate'].setErrors({'incorrect': false});
    this.transactionForm.controls['transactionDate'].setValue(new Date());
    this.transactionForm.controls['type'].setValue('Sales');
    this.transactionForm.clearValidators();
  }

It's easier to get type and transactionDate to be reset to a default value but I'm not sure what I can do about birthdate or bill Number above.将 type 和 transactionDate 重置为默认值更容易,但我不确定我可以对上面的生日或账单编号做些什么。 I tried the code above but on reset, the control is still red (and invalid).. which it should be in a new/original state.我尝试了上面的代码,但在重置时,控件仍然是红色的(并且无效)......它应该处于新的/原始状态。 How can I fix this?我怎样才能解决这个问题?

使用reset('')并通过markAsPristine()将整个表单组设置为pristine markAsPristine()应该可以解决问题

Reset method重置方法

Reset the FormGroup, marks all descendants are marked pristine and untouched , and the value of all descendants to null.重置 FormGroup,将所有后代标记为原始和未触及,并将所有后代的值设为 null。

this.transactionForm.reset();

or if you want to pass a value to the from it 's the same like use setValue method after form reset;或者如果你想将一个值传递给它,就像在表单重置后使用setValue方法一样;

this.transactionForm.reset({contriolName01:'value..',controlName02:'value..'});

style the invalid touched vaild样式无效的触摸有效

.ng-invalid.ng-touched {
  border-color: red;
}

stackblitz example堆叠闪电战示例

Reset Form in Angular在 Angular 中重置表单

Method #1 (❌ Not preferrred)方法#1(❌不推荐)

HTML: HTML:

<button type="reset" >Clear Form </button> 

Method #2 (✅ preferred)方法#2(✅首选)

Typescript:打字稿:

fg = new FormGroup({name:new FormControl(''),
                     nestedFg : new FormGroup({abc : new FormControl('')})
                   })  
fg.reset()  // formGroup reset 
fg.get('name').reset() // formControl reset 
fg.get('nestedFg').reset()  // Nested formGroup reset
fg.get('nestedFg').get('abc').reset() // Nested formControl reset 

Method #1 note: it is pertinent to mention that don't use this method as type reset should avoid to use as per mozilla docs for more Info方法 #1 注意:有必要提及不要使用此方法,因为类型重置应避免按照 mozilla 文档使用以获取更多信息

Method #2: give more control on forms use formGroup which gives more control方法#2:对表单给予更多控制使用 formGroup 给予更多控制

None of the above answers worked for me, so I realized it had to do something with using material elements for form group controls.以上答案都不适合我,所以我意识到它必须通过将材料元素用于表单组控件来做一些事情。

I found this bug: https://github.com/angular/material2/issues/4190我发现了这个错误: https : //github.com/angular/material2/issues/4190

Adding something like this fixed it for me:添加这样的东西为我修复了它:

@ViewChild(FormGroupDirective) myForm;

sendDataToBackendAndResetForm() {
  // TODO: send data to backend
  if (this.myForm) {
    this.myForm.resetForm();
  }
}

I don't why reset didn't work for me until I passed an empty string.我不明白为什么在我传递了一个空字符串之前重置对我不起作用。 I wanted to reset a particular control.我想重置一个特定的控件。 Form was built with formbuilder and Angular 8. Form 是用 formbuilder 和 Angular 8 构建的。

Did something like this.transactionForm.get('billNumber').reset('')做了类似this.transactionForm.get('billNumber').reset('')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM