【问题标题】:how to prevent default behavior on click event in MatHorizontalStepper如何防止 MatHorizo​​ntalStepper 中单击事件的默认行为
【发布时间】:2019-03-31 13:44:07
【问题描述】:

我正在使用 Angular 应用程序。我有一个 MatHorizo​​ntalStepper,我想知道如何防止 next 和 back 按钮的默认行为。我以为我可以在点击处理程序中使用 event.preventDefault() 但这似乎不起作用。

这是按钮的 HTML:

<mat-horizontal-stepper>
…
  <button *ngIf="scrnIndex > 0" mat-raised-button matStepperPrevious type="button" (click)="backClicked($event, scrnIndex)">Back</button>
  <button *ngIf="scrnIndex < formScreens.length - 1" mat-raised-button matStepperNext type="button" (click)="nextClicked($event, scrnIndex)”>Next</button>
…
</mat-horizontal-stepper>

这是点击处理程序:

nextClicked(event, screenIndex) {
  event.preventDefault();
  this.validateCurrentPage(screenIndex);
}

我要做的是阻止步进器转到下一页,直到用户在响应页面上的任何无效值时出现的对话框上单击“确认”(这意味着我们不会一定要阻止用户继续使用无效值,但我们确实希望通过对话框警告他们)。

函数 ValidateCurrentPage() 进行检查并在检测到任何无效值时弹出一个对话框:

ValidateCurrentPage() {
    …
  const dialog = new GeneralDialogModel(
    'Past Dates/Times Detected',  // Title
    'One or more dates and/or times are in the past. Is this intentional?', // Content text
    'Yes',                        // Confirm button text
    'No');                        // Cancel button text
  const dialogRef = this._dialog.open(GeneralDialogComponent, { data: dialog });
  dialogRef.afterClosed().subscribe(result => {
…
  });
…
}

因为对话框在不同的线程上运行,validateCurrentPage() 在用户点击“是”或“否”之前返回,这意味着点击事件处理程序在用户点击“是”或“否”之前返回。然后点击事件的默认行为发生:步进器进入下一页。 event.peventDefault() 并没有阻止它。

我想做的是停止默认行为,然后在用户单击“是”时以编程方式转到下一页。但我需要知道如何停止默认行为(或暂停它,直到我以编程方式取消暂停它)才能做到这一点。

【问题讨论】:

标签: angular dialog preventdefault stepper


【解决方案1】:

一种解决方案:

  1. 删除该按钮上的 matStepperNext 指令
  2. 使用@ViewChild(MatStepper, {static:true}) 访问组件打字稿文件中的步进器并将其存储在成员变量(例如“stepper”)中 - 请注意,在以后的 Angular 版本中需要静态字段。
  3. 在ValidateCurrentPage()中,调用this.stepper.next()触发步进器进入下一步。

希望对您有所帮助!更多草原信息:https://material.angular.io/components/stepper/api

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-20
    • 1970-01-01
    • 2018-07-31
    • 1970-01-01
    • 2017-03-18
    • 2017-11-09
    • 1970-01-01
    相关资源
    最近更新 更多