【问题标题】:Angular 2 material mat-select calling multiple timesAngular 2材料垫选择多次调用
【发布时间】:2020-02-04 13:05:58
【问题描述】:

我正在使用角材料。当我使用 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,但有时它仍会在没有任何选择的情况下进入条件。有人请帮我解决这个问题

【问题讨论】:

    标签: angular angular-material2


    【解决方案1】:

    下面的代码我还没有测试过,但是我觉得你可以这样使用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。

    【讨论】:

    • 是的,我也试过这个,但没有调用 updateState() 方法
    • 我尝试了代码并且成功了,记住事件是 selectionChange。我用 Angular 5.2 进行了测试。
    • 我的代码中的 selectionChange 放错了位置。我在 mat-option 中使用而不是 mat-select。现在它的工作。谢谢
    • 工作得很好。谢谢!
    【解决方案2】:

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

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

    Demo for this

    【讨论】:

      猜你喜欢
      • 2018-05-05
      • 2018-06-01
      • 2021-02-17
      • 2018-04-30
      • 1970-01-01
      • 1970-01-01
      • 2019-03-11
      • 2020-07-05
      • 1970-01-01
      相关资源
      最近更新 更多