1
votes

I am struggling with mat-select and options in an Angular 6 project.

My use case is as follows:

I want to have a list of organizations drop down and save the selected organization (full object, not just the name)

  1. formControlName should be an object as i want to store the complete object on save with all of its properties - WORKING
  2. options are populated as an observable with the full object but displays only the name property - WORKING
  3. When loading the form i want to display the name of the organization that had been previously selected. - NOT WORKING

Everything works correctly except it shows blank value i.e. the options display all the organisations, when i select and organisation and save the full organization object is saved, but when i first load the form i want it show the name of the organisation previously selected and saved.

All of the posts i can seem to find are just working with a simply property not an object.

See Code Below (hope that makes sense). Any suggestions / guidance appreciated

<div [formGroup]="orderForm"> 
      <mat-form-field>
          <mat-label>Select Customer</mat-label>
          <mat-select formControlName="customer">
               <mat-option *ngFor="let organization of (organizations$| async)"
                   [value]="organization">
                       {{ organization.name }}
               </mat-option>
          </mat-select>
       </mat-form-field>
</div>
1

1 Answers

0
votes

The solution was quite simple in the end, which i found in this post Angular Material: mat-select not selecting default

Essentially I just used the placeholder, order is the underlying object that is used to populate the form and customer is just one of the properties on the form:

<mat-select formControlName="customer" [placeholder]="order.customer['name']">
   <mat-option *ngFor="let organization of (organizations$| async)"
       [value]="organization">
           {{ organization.name }}
    </mat-option>
</mat-select>