将mat-select绑定到onOpen事件

时间:2018-07-19 07:43:00

标签: javascript html angular

我试图将mat-select绑定到一个函数,该函数将调用java并获取必须显示为选项的数据。

但是(onOpen)事件不起作用,更准确地说,永远不会调用绑定到该事件的函数。

有人遇到这样的问题吗?

这是我的代码:

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

这是函数getData:

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

谢谢!

2 个答案:

答案 0 :(得分:0)

您的第一个问题是您应该删除它。从下面的行。

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

只写

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

另一个问题是,您可以在 select 元素内使用(单击)事件,它将仅调用一次。

看看我为您准备的Demo

一旦单击选择元素将其打开,它将仅调用一次函数。

答案 1 :(得分:0)

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

在您的ts文件中,使用以下代码

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

}

相关问题