Search code examples
javascriptangularformsformarrayformgroups

Angular - FormArray, how to reset a specific field of a formArray?


I can't figure out how to reset a single field of a FormArray, for example:

myForm = this.fb.group(
        {
            title: ["", [Validators.required, Validators.minLength(4)]],
            date: ["", Validators.required],
            pairs: this.fb.array(
                this.fPairs.map(f =>
                    this.fb.group({
                        score: [],
                        value: [],
                        valueRel: []
                    })
                )
            )
        },
        {
            validator: minMaxValidator
        }
    );

so my FormArray is an Array of 4 Objects as it's mapped from:

fPairs: Array<fPairs> = [
        {score: 0, value: 0, valueRel: 0},
        {score: 0, value: 0, valueRel: 0},
        {score: 0, value: 0, valueRel: 0},
        {score: 0, value: 0, valueRel: 0}
    ];

what I achieved so far, to reset this part of my form, is:

pairsControl= this.myForm.controls["pairs"] as FormArray;

and then use:

this.pairsControl.reset();

but this resets EVERY field of the FormArray, and what I want instead, is being able to reset only a specific field,

for example the "score" field of all 4 objects, while leaving intact the value and the valueRel fields

I tried this:

this.fixedPointsControl.reset(["score"]);

but what it does, is reset everything like the previous expression, so nothing changes!

What s the correct way to reset a specific field of a formArray?


Solution

  • Just create a pairs getter to get the pairs FormArray. Now in the resetField method set a parameter named fieldName that would expect the name of the filed on the pairs FormArray to reset

    Something like this:

    get pairs() {
      return (<FormArray>this.myForm.get('pairs'));
    }
    
    resetField(fieldName) {
      this.pairs.controls.forEach(group => group.get(fieldName).reset());
    }
    

    And then add these buttons to your template:

    <button (click)="resetField('score')">Reset Score</button> | 
    <button (click)="resetField('value')">Reset Value</button> | 
    <button (click)="resetField('valueRel')">Reset Value Rel</button>
    

    Here's a Working Sample StackBlitz for your ref.