Búsqueda de sitios web

angular - ¿Por qué se llama onSelectionChange dos veces?


Estoy usando Angular Material Autocomplete de la siguiente manera:

<mat-autocomplete #autocomplete="matAutocomplete" [displayWith]="displayFn" autoActiveFirstOption>
  <mat-option *ngFor="let option of filteredOptions$ | async" [value]="option" (onSelectionChange)="onSelectionChanged(option)" >
    {{displayFn(option)}}
  </mat-option>
</mat-autocomplete>    

Este es el controlador:

onSelectionChanged(option) {
  console.log('Selected ' + option.name);
}

Por alguna razón, onSelectionChanged() se llama dos veces. ¡La segunda vez con el valor antiguo! No entiendo por qué. ¿Qué está pasando aquí?

Seleccionar el artículo 1 y luego el artículo 2 y luego el artículo 3 imprimirá:

> Selected item 1
> Selected item 2
> Selected item 1  // The unwanted call with the old value
> Selected item 3
> Selected item 2  // The unwanted call with the old value

Respuesta #1

Me estaba enfrentando al mismo problema con una mat-option dentro de un mat-select y lo solucioné de esta manera:

Plantilla

<mat-select>
 <mat-option (onSelectionChange)="handleMetaSignalChange(metaSignal.name,$event);" *ngFor="let metaSignal of metaSignals" [value]="metaSignal">
  {{ metaSignal.name }}
 </mat-option>
</mat-select>

Código

 handleMetaSignalChange(metaSignal: string, event: any) {
    if (event.isUserInput) {    // ignore on deselection of the previous option
      console.log('Meta Signal Changed to ' + metaSignal + event.isUserInput);
    }
 }

Respuesta #2

el material tiene evento optionSelected que puedes usar

<mat-autocomplete #autocomplete="matAutocomplete" (optionSelected)="onSelectionChanged($event)" [displayWith]="displayFn" autoActiveFirstOption>
 <mat-option *ngFor="let option of filteredOptions$ | async" [value]="option" >
    {{displayFn(option)}}
 </mat-option>
</mat-autocomplete>  

y obtén tu valor de esa manera

onSelectionChanged(event) {
   console.log(event.option.value);
}

Respuesta #3

Si necesitas obtener todo el OBJETO y usar los valores de sus hijos en el componente:

1- Envía tanto object como $event del DOM al component.ts.

<!-- Printing out the country name and flag only -->

 <mat-autocomplete #auto="matAutocomplete">
   <mat-option 
      *ngFor="let country of filteredCountries$ | async" 
      [value]="country.name"
      (onSelectionChange)="getSelectedCountry(country, $event)">
      <img class="example-option-img" aria-hidden [src]="country.flag" height="25">
      <span>{{country.name}}</span>
   </mat-option>
 </mat-autocomplete>

2- Ahora actualiza tus valores en el component.ts

getSelectedCountry(country: ICountry, event: any): void {
   if (event.isUserInput) {    // ignore on deselection of the previous option
     console.log("Selected country name: ", country.name);
     console.log("Selected country code: ", country.code);
     console.log("Selected country flag link: ", country.flag);
}

Nota: ICountry es mi interfaz de país, la cual no es obligatorio tener.

Artículos relacionados