Angular 2材质mat-select多次调用

时间:2018-03-10 10:24:31

标签: angular angular-material2

我正在使用棱角分明的材料。当我使用onSelectionChange时,它在页面加载或我更改选择时多次调用。有人可以帮助我。

 <mat-form-field>
   <mat-select id="stateSelect" name="stateSelect" class="form-control" 
               placeholder="State Select" [(ngModel)]="myModel.state" required>
     <mat-option (onSelectionChange)="updateState($event)" *ngFor="let state of stateList" [value]="state.code">
       {{ state.value }}
     </mat-option>
   </mat-select>
   <mat-error>State is required</mat-error>
 </mat-form-field>

 // In my ts file
 updateState(event: any) {
   // my code
 }

我已经使用event.isUserInput来检查true是否为false,但是有时它仍然进入条件而没有任何选择。有人请帮我这个

2 个答案:

答案 0 :(得分:2)

我还没有测试过以下代码,但我认为你可以这样使用select和option标签:

<mat-form-field>
  <mat-select id="stateSelect" name="stateSelect" class="form-control" 
      placeholder="State Select" [(ngModel)]="myModel.state" (selectionChange)="updateState($event)" required>
    <mat-option *ngFor="let state of stateList" [value]="state.code">
      {{ state.value }}
    </mat-option>
  </mat-select>
  <mat-error>State is required</mat-error>
</mat-form-field>

在mat-select中使用 selectionChange 事件而不是mat-option中的 onSelectionChange 。有关详细信息,请参阅材料documentation

答案 1 :(得分:0)

我推荐@ 4ndt3s的答案。 (为防止选择相同,compareWith

事件值onLangChange($event)具有用于指示面板是否打开的值。
没错。
因此,如果您需要允许选择相同的选项,
请参阅Trigger event on re-selecting same value on mat-select

Demo for this

相关问题