【问题标题】:onSelectionChange getting called twice in AngularonSelectionChange 在 Angular 中被调用两次
【发布时间】:2018-10-21 18:21:54
【问题描述】:

我正在尝试在select 上附加onSelectionChange 事件,如下所示:

   <mat-form-field class="full-width languageDiv" appearance="outline" *ngIf="languages && selectedLanguage">
          <mat-label>Language</mat-label>
          <mat-select [(value)]="selectedLanguage">
            <mat-option *ngFor="let language of languages" [value]="language" (onSelectionChange)="onLangChange($event)">
              {{language}}
            </mat-option>
          </mat-select>
        </mat-form-field>

这里是onLangChange 方法

 onLangChange(e) {
    console.log(e);
        const languageSelected = e.source.value;
        if( this.selectedLanguage !== languageSelected){

            this.selectedLanguage = (languageSelected);

        }
  }

这里是stackblitz 链接: StackBlitz

对于选择的每一次更改,onLangChange 都会被调用两次,这会扰乱我的其他逻辑(此处未提及以保持代码简单)。为什么这会被调用两次?

【问题讨论】:

    标签: angular


    【解决方案1】:

    您应该如下使用 ngModel 和 ngModelChange,原因是您在 mat-option 上使用 onSelectionChange,而它应该在 mat-select 上。如下所示,最好使用 ngModelChange,

     <mat-select [(ngModel)]="selectedLanguage" (ngModelChange)="onLangChange($event)">
        <mat-option *ngFor="let language of languages" [value]="language">
            {{language}}
        </mat-option>
    </mat-select>
    

    DEMO STACKBLITZ

    【讨论】:

    • 完美运行,非常感谢。您附加的stackblitz 链接不起作用,它只有以前的代码。
    • 我很好奇,您说“最好使用ngModelChanges” - 为什么?官方文档建议使用selectionChange
    • 请注意,当表单的其余部分使用反应式表单方法时,这不是 Angular 7 中用于单个控件的选项。
    【解决方案2】:

    在名为 isUserInput 的键值与布尔值不同时会触发 2 个事件。

    true,如果是选择事件

    false,如果是取消选择事件

    在您的函数中,尝试添加如下 if 条件

    onLangChange(e) {
        console.log(e);
        if (e.isUserInput) { // isUserInput is true
            const languageSelected = e.source.value;
            if( this.selectedLanguage !== languageSelected){
    
                this.selectedLanguage = (languageSelected);
    
            }
         }
      }
    

    【讨论】:

      【解决方案3】:

      我推荐@Sajeetharan 的回答。 (为了防止相同的选择,compareWith

      根据上面的示例代码,onLangChange($event) 的事件值具有指示面板是否打开的值。(在我的示例代码中,ir 重命名为 onSelectionChange($event)
      因此,如果您需要允许选择相同的选项,
      参考这个,Trigger event on re-selecting same value on mat-select

      Demo for this

      【讨论】:

        猜你喜欢
        • 2021-04-09
        • 2019-03-26
        • 2017-03-13
        • 1970-01-01
        • 2019-11-16
        • 2018-03-16
        • 2017-04-02
        • 1970-01-01
        • 2011-12-10
        相关资源
        最近更新 更多