问题
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
回答1:
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)
}
}
回答2:
Multiple ways of solving this. One could be:
<mat-select placeholder="Persons" (change)="notes$.next($event.value)">
<mat-option *ngFor="let person of persons" [value]="person.notes">
{{ person.name }}
</mat-option>
</mat-select>
And the second one:
<mat-select #noteField placeholder="Notes">
<mat-option *ngFor="let note of notes$ | async" [value]="note">
{{ note.yy }}
</mat-option>
</mat-select>
On component:
notes$ = new Subject<any[]>();
来源:https://stackoverflow.com/questions/50113124/how-to-retrieve-an-array-of-objects-in-two-mat-select-with-angular-4