Issue
i have an array of objects person,and each one contain an array field of objects notes
[{ "id": 0 ,name : "aa" ,notes:[ {"id":0 , "xx" : 14} ,{ "id" : 1 , "xx" : 12} ,{"id" : 1 , "zz" : 9 } ]} ,
{"id": 2 ,name : "bb" , notes:[{ "id":0 , "xx" :"7"}, { "id" : 1 , "xx" : 17 }]} ,
{"id": 3 , name : "cc" , notes:[ "id":0 ,"name" : "xx" : 18 ]} ]
i want to retrive the array of persons in the first mat-select and bind the select element to objects then change the second mat-select list values with notes array approriate to the object selected in the first list
Solution
with reactiveForms and simple select
<!--is common write *ngIf="dataForm" to avoid errors at first -->
<form *ngIf="dataForm" [formGroup]="dataForm" (submit)=submit(dataForm)>
<select formControlName="person">
<!--is necesary using [ngValue] -->
<!-- notice that the value is an object -->
<option *ngFor="let per of data" [ngValue]="per">{{per.name}}</option>
</select>
<select formControlName="note">
<!--notice as the options is ngFor of "dataForm.get('person') -->
<option *ngFor="let not of dataForm.get('person').value.notes"
[ngValue]="not.id">{{not.xx}}</option>
</select>
</form>
{{dataForm?.value |json}}
//in component.ts
data=[{ "id":....]
//When you create the form, see that I put a value by defect
this.dataForm=this.fb.group({
person:this.data[0],
note:this.data[0].notes[0]
});
//other can be
this.dataForm=this.fb.group({
person:{notes:[]}, //notice that create an object with property "notes"
note:null
});
submit(dataForm)
{
//See that "dataForm.value.person" is an object,
//so you create a object "data" with only
if (dataForm.valid)
{
let data={
person:dataForm.value.person.id,
note:dataForm.value.note
}
//do something with "data"
console.log(data)
}
}
Answered By - Eliseo
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.