onselected 事件在 md-select 在 Angular 4

onselected event in md-select in Angular 4

我想在使用 md-select 选择值时调用打字稿中的函数。在 material 设计中用于此目的的 属性 是什么?

   <md-select placeholder="State">
       <md-option *ngFor="let state of states" [value]="state.code">{{ state.name }}
   </md-option>

文档对这类事情非常开放:

https://material.angular.io/components/select/api

@Output()
change
Event emitted when the selected value has been changed by the user.

<md-select (change)="wasThatSoHard($event)"></md-select>

对于 Material 版本 >= 6

mat-select 上使用 (selectionChange) 事件。

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

在事件方法中,$event.value包含当前选中的[value]。参考official documentation.

@Output() selectionChange: EventEmitter< MatSelectChange >

Event emitted when the selected value has been changed by the user.

这里是link到Stackblitz Demo


对于 Material 版本 < 6

使用(change)输出事件。

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

另一种方法是在 <md-option>:

上使用 (onSelectionChange) 事件
<md-select placeholder="State">
  <md-option *ngFor="let state of states" [value]="state.code" 
             (onSelectionChange)="anotherMethod($event, state)">
    {{ state.name }}
  </md-option>
</md-select>

Link 到 Stackblitz Demo.

只是为使用最新版本 material 的人添加并搜索解决方案,在@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>

对于大于 6 的 material 版本使用 (selectionChange) 而不是 change

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

试试这个,

html

<mat-label>Select a Category</mat-label>
<mat-select formControlName="category" name="category 
         (selectionChange)="onChangeCategory($event)">
    <mat-option *ngFor="let category of categories" [value]="category.value">
            {{category.viewValue}}
    </mat-option>
</mat-select>

打字稿

onChangeCategory(event) {
    console.log(event.value);
}