10

I use md-autocomplete angular/material: 2.0.0-beta.5 in my Angular application. With the latest release the selected method has been replaced by onSelectionChange.

The first time a value from the drop down is selected, the associated method is triggered only once, but if I select a new value from the drop down, it is selected twice (the second time having the previous value).

The logic was working correctly with the previous version.

template

<md-autocomplete #panel="mdAutocomplete" [displayWith]="displayFn">
   <md-option (onSelectionChange)="selected(country)" *ngFor="let country of filteredCountries | async" [value]="country">
    <div class="selector-elements">
      <span>
          <img [src]="getFlagPath(country.code)" [width]="24" [height]="24" /> 
      </span>    {{ country.name }}
      </div>
</md-option>

controller

export class CountrySelector implements OnInit, ControlValueAccessor {

// ...

initCountries() {
    this.countryList = countryNames;

    this.filteredCountries = this.formControlName.valueChanges
        .startWith(null)  //-> OnInit the countries are filtered by null, hence all results are returned.
        .map(country => {
            return country && typeof country === 'object' ? country.name : country
        })
        .map(name => name ? this.filter(name) : this.countryList.slice());
}

filter(val: string): ICountry[] {
    //Regex to match with the first letters of the country name with the passed value.
    return this.countryList.filter(country => new RegExp(`^${val}`, 'gi').test(country.name));
}

resetCountrySelection(){
    let country = new Country();
    this.formControlName.setValue(country);
    this.propagateChange(country);
}

writeValue(country: Country): void {
    if (country) {
        this.formControlName.setValue(country);
    }
}

selected(country: ICountry) {
   // Here it gets triggered twice when a new element is chosen
   this.propagateChange(country);
}

propagateChange = (_: any) => { };

registerOnChange(fn: any) {
    this.propagateChange = fn;
}

}
Francesco
  • 9,947
  • 7
  • 67
  • 110

1 Answers1

29

What is happening is onSelectionChange fires both for the new selected, and the one being unselected, in that order. If you add the $event to your call like so

(onSelectionChange)="selected($event, country)"

you can then check if it is the selected one by looking at the source like this

selected(event: MdOptionSelectionChange, country: ICountry) {
   if (event.source.selected) {
       this.propagateChange(country);
   }
}
Joo Beck
  • 1,863
  • 1
  • 18
  • 21
  • good point. Actually this was at the base of the method renaming (as before only on the selected item it was fired). Thanks for noticing it! – Francesco May 19 '17 at 06:58
  • Glad to be of service! – Joo Beck May 22 '17 at 14:45
  • I would not count on the order of the events firing – Ricardo Saracino Nov 13 '18 at 20:15
  • 1
    You are correct, you shouldn't count on that order, but that ordering was part of the confusion of the original post. The solution provided works regardless of order. – Joo Beck Nov 14 '18 at 18:45
  • I don't get any event fired if I deselect an option. Any ideas how to catch when the user deselects an option? – tif Nov 21 '19 at 09:52
  • @tif the selectionChange should fire for any change. The answer listed here is for filtering out the de-select changes, so if you want the de-select, don't filter. If it's not that, you'd need to provide more information, and should likely be its own question. – Joo Beck Nov 21 '19 at 16:14