Ramu
Ramu

Reputation: 145

Cannot read property 'data' of undefined-using patchValue in sub formArray

I tried to render the cat_name dynamically by selecting the select box. but i am not able the render the cat_name by using the patchValue. Below is my code to render the sub formArray.

By selecting the select box using change event i got the firstname based on value i have filter the json array and i got particular formarray.

It having the data formArray i tried to render the cat_name while selecting the select box but i am not getting. Below is my code

selectarch(cat){

this.test=this.users.filter(data =>data.firstname === cat.target.value);

let arr = <FormArray>this.myForm.controls.users;

arr.controls[0].patchValue({firstname:this.test[0].firstname,lastname:this.test[0].lastname,street:this.test[0].street});

let arr2 = <FormArray>this.myForm.controls.users[0].data;
arr2.controls[0].patchValue({cat_name:this.test[0].data[0].cat_name});

}
<select (change)="selectarch($event)">
<option>Select</option>
<option [value]="res.firstname" *ngFor="let res of users">{{res.firstname}}</option>
</select> 

Below is my CODE URL CODE URL

Below is json users array.

users = [ { "firstname": "ramu", "lastname": "mothukuri", "city": "chennai", "street": "ramu sivan koiil street", "pin": "600024",
  "data":[{"cat_id":"1","cat_name":"yyy","category":"rrr"},{"cat_id":"2","cat_name":"zzz","category":"222"}] },
  { "firstname": "ravi", "lastname": "mothukuri", "city": "chennai", "street": "ravi sivan koiil street", "pin": "600024","data":[{"cat_id":"1","cat_name":"ddd","category":"aaa"},{"cat_id":"2","cat_name":"aa","category":"333"}] },
  { "firstname": "manu", "lastname": "mothukuri", "city": "chennai", "street": "manu sivan koiil street", "pin": "600024","data":[{"cat_id":"1","cat_name":"jjj","category":"999"},{"cat_id":"2","cat_name":"bbb","category":"666"}] }
  ]

Upvotes: 3

Views: 10930

Answers (2)

Arun Kumaresh
Arun Kumaresh

Reputation: 6311

you should get the data formarray to patch the value of cat_name

try this

const users = this.myForm.get(['users', 0, 'data']) as FormArray;

users.controls[0].patchValue({cat_name:this.test[0].data[0].cat_name});

Working example

Upvotes: 2

sabithpocker
sabithpocker

Reputation: 15566

let users = <FormArray>this.myForm.get('users');
// users is the FormArray as I understood from your code
users.at(0).get('data').patchValue({cat_name:this.test[0].data[0].cat_name});
// at(0) will give the formGroup at index 0 of formArray
// get('data') to get formControl of formGroup

Your formGroup is like:

this.fb.group({
    users: this.fb.array([fb.group({
                firstname: this.users[0].firstname,
                lastname: this.users[0].lastname,
                street: this.users[0].street,
                data: dataArr
    })])
})

Upvotes: 0

Related Questions