0

I Want to patch a value of an array inside another array, I can achieve it by using

this.myForm.value.array1[index1].array2[index2].type = type;

although it doesn't update the forms value on the screen only in the form values in code, I the code below to patch values in the first array and it updates the values on the screen i just cant write it to be able to reach the second array

(<FormArray>this.myForm.controls['array1']).at(index1).get("type").patchValue(type);

thanks :)

0

1 Answer 1

3

If you not use setValue, Angular change the value but Angular not reflect in the input, don't mark the input as touched...

So

((this.myForm.get('array1') as FormArray)
       .at(index1).get('array2') as FormArray)
       .at(index2).get("type").patchValue(type);

or

this.form.get('array1.'+index1+'.array2.'+index2+'.type').patchValue(type)

NOTE1: using get to access at element of an array is the way array1.index, so array1.0 get the first element of the array, array1.1 the second one...

NOTE2: is recomended use the method get(name) vs controls[name]

Update I don't know yours requeriments, but If you want simple control an array of arrays of an object you can use a FormArray of FormArrays of FormGroup.

Well, some like

formArray=new FormArray([
      new FormArray([
        new FormGroup({
           type:new FormControl('uno')
        }),
        new FormGroup({
           type:new FormControl('dos')
        }),
      ]),
      new FormArray([
        new FormGroup({
           type:new FormControl('tres')
        }),
        new FormGroup({
           type:new FormControl('cuatro')
        }),
      ])
    ]) 

Can be mannage in an html as

<div *ngFor="let array of formArray.controls">
  <div *ngFor="let group of array.controls" [formGroup]="group">
    <input formControlName="type">
  </div>
</div>

In this case use

(this.form.at(0) as FormArray).at(1).get('type').patchValue('new');

see stackblitz

Sign up to request clarification or add additional context in comments.

2 Comments

Nice technique @Eliseo ! for me it worked without the as FormArray. Something like: this.myForm.get('array1').at(index1).get('array2').at(index2).get("type").patchValue(type);
@VitaeAliquam, it's a old post (Ive learn some about Angular since time), You can concatenate string in function get, so you can use some like:this.myForm.get('array1.'+index1+'.array2.'+index2+'.type').patchValue(type)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.