Как получить массив объектов в два mat-select с угловым 4 - PullRequest
0 голосов
/ 01 мая 2018

у меня есть массив объектов person, и каждый из них содержит поле массива объектов 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 ]} ]

Я хочу получить массив лиц в первом мат-выделении и связать элемент select с объектами, а затем изменить значения второго списка мат-выбора с массивом примечаний, соответствующим объекту, выбранному в первом списке

Ответы [ 2 ]

0 голосов
/ 01 мая 2018

с реактивными формами и простым выбором

<!--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)
        }
   }
0 голосов
/ 01 мая 2018

Несколько способов решения этой проблемы. Можно было бы:

          <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[]>();
...