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...
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 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.
<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())
});
}