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;
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With