Reset form with default values
Asked Answered
T

2

13

In my angular application, I added default value of Id as 0. but when user reset the form, it cleared off.

how to reset the form with default values remaining?

here is my form :

this.createForm = this.formBuilder.group({
    'Id': new FormControl({ value: 0, disabled: true }, [Validators.required])
});

I tried like this:

dismissEditPop() {
  this.createForm.reset();
  this.createForm.setValue({ //setting back not working!!
    Id: 0
  });
  this.modalBackdrop = false;
  this.editPopup = false;
  this.deletePopup = false;
  this.addRowData = false;
}
Tuantuareg answered 10/7, 2019 at 13:30 Comment(0)
A
14

By default the .reset() method, marks the form as pristine and untouched, and sets it's value to null.

To reset it with another value, pass the wanted formState like this: this.formGroup.reset({id: 0}.

Further information is in the documentation.

Apparently answered 10/7, 2019 at 13:35 Comment(0)
R
18

With Angular 14, Typed Reactive Forms have been introduced, alongside with the possibility to declare a form-control as non-nullable (Example from Angular docs):

const email = new FormControl('[email protected]', {nonNullable: true});
email.reset();
console.log(email.value); //[email protected]

This will cause the control to reset to its initial value, instead of null. If you want to specify {nonNullable: true} for every control of your FormGroup you can avoid the boilerplate code and use a NonNullableFormBuilder by injecting a NonNullableFormBuilder instead of a FormBuilder into the component containing the form:

export class FormComponent{
   constructor(private fb: NonNullableFormBuilder) {}
   const email = fb.group({
       email: '',
       password: '',
   })
}

Alternatively, you can call fb.nonNullable.group({...}), if fb is a normal FormBuilder.

Reaction answered 30/3, 2023 at 15:12 Comment(2)
Very useful. No need to use the old way to handle setting initial value to formGroup or formControlHarod
This is what I was looking for. Thanks!Antiproton
A
14

By default the .reset() method, marks the form as pristine and untouched, and sets it's value to null.

To reset it with another value, pass the wanted formState like this: this.formGroup.reset({id: 0}.

Further information is in the documentation.

Apparently answered 10/7, 2019 at 13:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.