Angular 4中md-select中的onselected事件

Kar*_*mar 31 angular-material angular-material2 angular

我想在使用md-select选择值时在typescript中调用函数.在材料设计中用于此目的的属性是什么?

   <md-select placeholder="State">
       <md-option *ngFor="let state of states" [value]="state.code">{{ state.name }}
   </md-option>
Run Code Online (Sandbox Code Playgroud)

Fai*_*sal 96

材料版本更新> = 6

使用该(selectionChange)事件mat-select.

<mat-form-field>
    <mat-select placeholder="State" (selectionChange)="someMethod($event.value)">
        <mat-option *ngFor="let state of states" [value]="state.value">
            {{ state.viewValue }}
        </mat-option>
    </mat-select>
</mat-form-field>
Run Code Online (Sandbox Code Playgroud)

在事件方法中,$event.value包含当前选中的[value].参考官方文档.

@Output()selectionChange:EventEmitter <MatSelectChange>

用户更改选定值时发出的事件.

这是一个工作更新演示的链接.


原始答案

使用(change)输出事件.

<md-select placeholder="State" (change)="someMethod()">
  <md-option *ngFor="let state of states" [value]="state.value">
    {{ state.viewValue }}
  </md-option>
</md-select>
Run Code Online (Sandbox Code Playgroud)

另一种方法是使用(onSelectionChange)事件<md-option>:

<md-select placeholder="State">
  <md-option *ngFor="let state of states" [value]="state.code" 
             (onSelectionChange)="anotherMethod($event, state)">
    {{ state.name }}
  </md-option>
</md-select>
Run Code Online (Sandbox Code Playgroud)

链接到工作演示.

  • (更改)已重命名为(selectionChange) (3认同)
  • 每个版本的语法都在变化。它不再有趣 (3认同)

小智 6

只是为使用最新版本材料并搜索解决方案的人添加,在 @Faisal 建议的答案中将 md 更改为 mat。

<mat-select placeholder="State" (change)="someMethod()">
  <mat-option *ngFor="let state of states" [value]="state.value">
    {{ state.viewValue }}
  </mat-option>
</mat-select>
Run Code Online (Sandbox Code Playgroud)

(selectionChange)对于大于 6 的材质版本,请使用change


Mau*_*ice 6

或者,您可以只在(click)上使用事件mat-option。当再次选择已选择的选项时,也会触发 click 事件。(change)或者(selectionChange)在这种情况下不会触发。

  • 对于未来的读者,最好不要在下拉菜单中使用“(单击)”,因为下拉菜单也可以通过按钮进行导航。(例如向下和向上按钮)。在这些情况下,不会触发“(click)”事件。这意味着您的处理程序不会被调用。在下拉菜单上使用“click”事件也是一个重要的可访问性反模式。 (2认同)