Amivit
Amivit

Reputation: 189

How to use Material2 autocomplete, when [value] is an object?

My autocompletion below worked fine, until I changed the [value] of md-option to the object itself, instead of wc.WorkcenterId. I can filter the list completely fine, but as soon as I click on one, for some reason the filterWorkcenters() method is triggered and a wc object is sent into it, crashing the component since I obviously can't toLowerCase() on an object (it expects just the wc.WorkcenterId). What can I do to fix this? I can't go back because I need my FormGroup ctrl values' to have the proper objects, not just properties.

My HTML:

<div class="col-md-offset-2 form-item">
  <md-form-field class="full-width">
    <input required mdInput placeholder="Old workcenter number" [mdAutocomplete]="auto" formControlName="oldWorkcenter">
    <md-autocomplete #auto="mdAutocomplete" style="max-height:500px !important;" [displayWith]="displayFormat">
      <md-option *ngFor="let wc of oldWorkcentersFiltered | async" [value]="wc">
        <span>No.: <b>{{ wc.WorkcenterId }}</b>, Type: <b>{{ wc.LineType }}</b></span>
      </md-option>
    </md-autocomplete>
  </md-form-field>
</div>

My TS:

onSelectPlant(plant: Plant) {
  this.oldWorkcentersFiltered = this.newLineForm.get('oldWorkcenter').valueChanges
    .startWith(null)
    .map(query => query ? this.filterWorkcenters(query) : this.oldWorkcenters.filter(x => x.PlantNumber === plant.PlantNumber).slice())
  this.getAllMonitorsForPlant(plant);
  this.newLineForm.get('oldWorkcenter').enable();
}

private filterWorkcenters(query: string) {
    console.log(query);

    const test = this.oldWorkcenters.filter(wc => {
      return wc.WorkcenterId.toLowerCase().indexOf(query.toLowerCase()) === 0;
    });

    return test;
}

Upvotes: 0

Views: 358

Answers (1)

Amivit
Amivit

Reputation: 189

I fixed it by changing

.map(query => query ? this.filterWorkcenters(query) : this.oldWorkcenters.filter(x => x.PlantNumber === plant.PlantNumber).slice())

to

.map(query => (typeof query === 'string') ? this.filterWorkcenters(query) : this.oldWorkcenters.filter(x => x.PlantNumber === plant.PlantNumber).slice())

Upvotes: 1

Related Questions