【问题标题】:Detect when mat-stepper validation fails检测 mat-stepper 验证何时失败
【发布时间】:2018-07-16 17:00:10
【问题描述】:

我们有一个线性的mat-horizontal-stepper,现在我们想在用户尝试继续忘记必填字段时显示MatSnackBar

CdkStepper 似乎默默地调用_anyControlsInvalidOrPending 并在任何输入无效时返回。

有人知道如何检测此事件吗?

调用stepper.next()stepper.previous()step.select()时必须检测到

【问题讨论】:

    标签: angular validation angular-material2 angular-material-stepper


    【解决方案1】:

    一个肮脏的解决方案是

      ngAfterViewInit() {
        // when clicking on the step header
        this.stepper._steps.forEach((step) => {
          this.addPriorValidyCheckToFunction(step, 'select');
        });
        // when calling previous and next function
        this.addPriorValidyCheckToFunction(this.stepper, 'next');
        this.addPriorValidyCheckToFunction(this.stepper, 'previous');
      }
    
      addPriorValidyCheckToFunction(object, functionName) {
        // keep reference to AppComponent
        let self = this;
        // keep reference to original function
        let oldFunction = object[functionName];
        // replace original function
        object[functionName] = function () {
          // remember step before calling the function
          let oldStep = self.stepper.selected;
          // call the original function
          oldFunction.call(object);
          // if step did not change and form is invalid, show the message
          if (oldStep == self.stepper.selected && !self.stepper.selected.stepControl.valid) {
            self.snackBar.open("Fehler", "Bitte überprüfen Sie Ihre Eingaben", {
              duration: 2000,
            });
          }
    
        };
      }
    

    【讨论】:

      【解决方案2】:

      你需要添加一个“线性”属性

      <mat-vertical-stepper linear>
      

      如果表单无效,这将禁止导航到下一步。 如果表单无效,然后单击按钮添加验证功能,然后您可以显示警报或小吃栏或任何您想要的。

      【讨论】:

      • 然后,警报将仅在按钮被舔时显示,但在 mat-step-header 被单击时不显示。 :(
      【解决方案3】:

      如果您可以展示包含 mat-stepper 的组件和模板代码,那将很有帮助。但是,根据您的描述,我相信绑定到 selectionChange 事件对您有用。

      在包含步进器的模板中: stepper-example.component.html

      <mat-horizontal-stepper #stepper (selectionChange)="onStepChange($event)">
       <!-- your form -->
      </mat-horizontal-stepper>
      

      然后在您的组件中: stepper-example.component.ts

      import { Component, ViewChild } from '@angular/core';
      @Component({
        selector: 'stepper-example',
        templateUrl: './stepper-example.component.html'
      })
      export class StepperExampleComponent {
      @ViewChild('stepper') stepper;
      
      
      public onStepChange(event): void{
          //Some logic to validate your forms
        }
      }
      

      【讨论】:

        猜你喜欢
        • 2016-10-07
        • 2013-06-05
        • 1970-01-01
        • 2020-07-04
        • 1970-01-01
        • 2021-12-15
        • 2016-06-20
        • 2011-11-05
        • 1970-01-01
        相关资源
        最近更新 更多