Angular Forms: On autocomplete select, define form

2019-08-26 07:50发布

问题:

How to mask input for formcontrol name. HTML When the autocomplete is displayed you only see the airport.name. When users select an airport, I would like to display the airport.name in the input value but in formControl I would like to set the airport object as value because when I do a search I need more than a string to find data.

<mat-form-field>
    <input
      matInput
      formControlName="departure_airport"
      #el_departure_input
      class="[ flight-travel-form__airport__input ][ typography-sub-heading ]"
      value=""
      placeholder="Departure"
      [matAutocomplete]="auto"
    />
  </mat-form-field>

  <mat-autocomplete #auto="matAutocomplete">
    <mat-option *ngFor="let airport of active_search_suggestions$ | async" [value]="airport" class="ten-autocomplete">
      {{ airport.name.toLowerCase() }}
      <br>
      <span class="typography-small-text">{{ airport.iata_code }}</span>
      <div *ngIf="airport.object_type === 'airport_group'"> Any Airport</div>
    </mat-option>
  </mat-autocomplete>
</div>

回答1:

You could get the whole airport object by simply implementing (onSelectionChange)=selectedAirport(airport) for <mat-option>

Just created a stackblitz for it: https://stackblitz.com/edit/angular-nj3saw