如何使用角度4选择两个mat-select中的对象数组

时间:2018-05-01 07:56:02

标签: angular typescript angular-material2

我有一个对象数组,每个对象包含一个对象注释的数组字段

{"id": 2 ,name : "bb" , notes:[{ "id":0 , "xx" :"7"}, { "id" : 1 , "xx" : 17 }]} , 
 {"id": 3 , name : "cc" , notes:[ "id":0 ,"name" : "xx" : 18 ]} ]

{{1}}

我想在第一个mat-select中检索数组,并将select元素绑定到对象,然后将notes数组的第二个mat-select列表值更改为第一个列表中选择的对象

2 个答案:

答案 0 :(得分:0)

解决这个问题的多种方法。一个可能是:

          <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>

在组件上:

notes$ = new Subject<any[]>();

答案 1 :(得分:0)

使用reactiveForms和简单选择

<!--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

    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)
        }
   }