如何在角度为 4 的两个 mat-select 中检索对象数组 [英] How to retrieve an array of objects in two mat-select with angular 4
本文介绍了如何在角度为 4 的两个 mat-select 中检索对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个对象数组person,每个对象包含一个对象notes数组字段
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 ]} ]
我想检索第一个 mat-select 中的人员数组并将 select 元素绑定到对象,然后使用与第一个列表中选择的对象相适应的 notes 数组更改第二个 mat-select 列表值
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
推荐答案
with reactForms 和 simple select
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}}
//在component.ts中
//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)
}
}
这篇关于如何在角度为 4 的两个 mat-select 中检索对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文