Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reset form with default values

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;
}
like image 540
user2024080 Avatar asked Jan 22 '26 20:01

user2024080


1 Answers

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.

like image 85
Mar H. Avatar answered Jan 24 '26 16:01

Mar H.