简体   繁体   中英

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() {
    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. 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.

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;

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

Method #1 (❌ Not preferrred)

HTML:

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

Method #2 (✅ preferred)

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

Method #2: give more control on forms use formGroup which gives more control

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

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.

Did something like this.transactionForm.get('billNumber').reset('')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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