Home > database >  How to reset the formArray values to default values ?since form.reset() makes it null
How to reset the formArray values to default values ?since form.reset() makes it null

Time:03-04

I am new to angular and I have a form with these fields.

 this.catform = new FormGroup({
  name: new FormControl('', Validators.required,),
  source: new FormControl('', Validators.required),
  event: new FormControl('', Validators.required),
  cond:  this.fb.array([this.Cond()], Validators.required)     
});

 Cond() : FormGroup {
return this.fb.group({
  disp : new FormControl(1),
  field: new FormControl('', Validators.required),
  ct: new FormControl('', Validators.required),
  value: new FormControl('', Validators.required),
  ot : 'AND'
});
}

After submitting the form, I do the this.catform.reset(), but this resets the "disp" and "ot" to null, and thus makes my form have the values to null. Now when I submit this form again, it is unsuccessful in the backend since those values are null in the form but the backend doesnt accept this creation.So I want these to be as the ones which I have mentioned above, and I don't have these 2 fields in the HTML template, so I cannot edit them from the HTML template. Please if anyone could suggest some way.

CodePudding user response:

Convert the following code into a method. And when you want to reset, just call the method and assign it to this.catform

new FormGroup({
    name: new FormControl('', Validators.required,),
    source: new FormControl('', Validators.required),
    event: new FormControl('', Validators.required),
    cond:  this.fb.array([this.Cond()], Validators.required)
});

Like this:

this.catform=this.getFormgroup();

private getFormgroup() {
    return new FormGroup({
    name: new FormControl('', Validators.required,),
    source: new FormControl('', Validators.required),
    event: new FormControl('', Validators.required),
    cond:  this.fb.array([this.Cond()], Validators.required)
    });
}
  • Related