Binding a Mat-Select to an onOpen Event

I'm trying to bind a mat-select to a function which will call java and get the data that has to be shown as options.

However the (onOpen) event doesn't works , to be more accurate the function bound to it is never called.

Does anyone had an issue like this one ?

Here is my code :

 <mat-form-field>
      <mat-select placeholder="Select Year of the Report" (onOpen)="getData(0)">
        <mat-option *ngFor="let year of this.years">
          {{year}}
        </mat-option>
      </mat-select>
    </mat-form-field>

Here is the function getData:

getData(ref: number) {
    console.log('it Works !');
    this.recommendationService.getRecommendationFilters(ref).subscribe((data: any[]) => {
      this.years = data;
      console.log(data.toString())
    });
  }

Thank You !

2

2 Answers

you'r first problem is that you should remove this. from below line.

    <mat-option *ngFor="let year of this.years">

just write

    <mat-option *ngFor="let year of years">

The other problem is that you can use (click) event inside you'r select element and it will call only once.

look at Demo that I have prepare for you.

As soon as you click on the select element to open it, it will call function just once.

4
   <mat-form-field>
  <mat-select placeholder="Select Year of the Report" (change)='getData($event)'>
    <mat-option *ngFor="let year of years" value= 0>
      {{year}}
    </mat-option>
  </mat-select>
</mat-form-field>

in your ts file use below code

getData(event: any) {
ref = event.target.value;
console.log('it Works !');
this.recommendationService.getRecommendationFilters(ref).subscribe((data: any[]) => {
  this.years = data;
  console.log(data.toString())
});

}

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Sarah Jenkins

Sarah Jenkins

Senior Technology Editor & AI Specialist

Sarah Jenkins is a veteran tech journalist with over 12 years of experience covering artificial intelligence, mobile innovations, and digital ethics. Her insights have appeared in leading technology publications worldwide.

Share this article
Twitter Facebook Pinterest