0

I need to react on option selection. My problem is that this component is not emitting event (selectionChange output is not emitting new events) when I have selected option A, and I open select pane and select option A again. The event is not fired because selection is not changed but I need in my use case to fire an selection change event in this case. Does somebody know how to do this? Is there any way to override selectionModel in this mat-select component? I have a list of links and after selecting any of them I need to react even when user select the same link again. I'm using @angular/core@5.2.5 and @angular/material@5.2.1.

Here is the template with this component that I want to use:

<mat-form-field>
    <mat-select placeholder="Search history"
        [disabled]="(links | async).length === 0"
        [value]="(links | async).length > 0 ? (links | async)[0] : null"
        (selectionChange)="onSearchHistorySelect($event.value)">
        <mat-option *ngFor="let l of links | async" [value]="l">{{l.title}}</mat-option>
    </mat-select>
</mat-form-field>
Marcin Kapusta
  • 5,076
  • 3
  • 38
  • 55
  • Use an empty option to start with, or make your own component. But I'm not even sure that HTML allows what you want, I think you can't trigger an event on same option change. –  Jun 04 '18 at 13:38
  • 1
    If you are using `[ngModel]` then it'll support `(ngModelChange)`. try that then. – windmaomao Jun 04 '18 at 13:48
  • I'm not using any forms and model for this. Just link selector for navigation. I updated question with template. – Marcin Kapusta Jun 04 '18 at 13:51

1 Answers1

0

You can add a click event to your option, so the function will be called even if the option is already selected.

<mat-form-field>
    <mat-select [(ngModel)]="status">
      <mat-option *ngFor="let option of options" [value]="option.value (click)="myFunction()">
        {{ option.name }}
      </mat-option>
    </mat-select>
</mat-form-field>

The only problem I found with this is that you can't give the value of the selected option to the function (or at least I didn't find a way). But you can work around that by binding the value to a property in your class with ngModel.

Then in your function you can just call this property (in my case this.status).

myFunction() {
  console.log(this.status);  // Do stuff with your selected value
}

Hope this is what you are looking for.

Emmy
  • 3,493
  • 2
  • 16
  • 25
  • 1
    I have a feeling that this will not work with selecting by using keyboard only. – Marcin Kapusta Jun 13 '18 at 07:24
  • You can pass selected `option` to the function by using it like this. If `option` is scoped variable in the `*ngFor` loop and in Your example it is: `(click)="myFunction(option)"` – Marcin Kapusta Jun 13 '18 at 07:27