Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

md-autocomplete onSelectionChange fired twice

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;
}

}
like image 223
Francesco Avatar asked May 18 '17 20:05

Francesco


1 Answers

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);
   }
}
like image 70
Joo Beck Avatar answered Oct 12 '22 17:10

Joo Beck