【问题标题】:How to show modal confirmation in CanDeactivate in Angular2 application?如何在 Angular2 应用程序的 CanDeactivate 中显示模态确认?
【发布时间】:2017-08-25 20:42:57
【问题描述】:

我有一个 Angular2 应用程序。它的一个组件实现了 CanDeactivate 接口,以确认用户离开页面的导航。下面是路由守卫的实现:

export class DeactivateGuard implements CanDeactivate<MyComponent> {
  canDeactivate(component: MyComponent) {
  let can = component.canDeactivate();
  return can;
  }
}

这是组件的代码:

canDeactivate() {
if (confirm("Are you sure you want to navigate away?")) {      
  return true;
}
else {
  return false;
}
}

现在,我想显示一个自定义模式窗口,而不是浏览器的确认框。我用 Telerik 的 Kendo UI 构建了这样的窗口:

<kendo-dialog title="Please confirm" *ngIf="userConfirm">
    Are you sure you want to navigate away?
    <kendo-dialog-actions>
        <button kendoButton class="k-button" (click)="closeConfirm('no')">No</button>
        <button kendoButton class="k-button" (click)="closeConfirm('yes')" primary="true">Yes</button>
    </kendo-dialog-actions>
</kendo-dialog>

如果我在代码中的任何位置设置 userConfirm = true,则此模式窗口有效,canDeactivate() 方法除外。

canDeactivate() {
this.userConfirm = true; //Does not work. The modal does not show up.
}

如何使用此模式窗口获取用户输入?

谢谢。

【问题讨论】:

  • userConfirm 是一个全局变量。我可以确认模态窗口有效。我可以从代码中的其他地方激活它,但不能在 canDeactivate()
  • 这是我对类似问题的解决方案:stackoverflow.com/questions/46433195/…

标签: angular angular-router-guards


【解决方案1】:

我认为您在从您的身份验证守卫执行component.canDeactivate(); 时失去了作用域。试试这个:

export class DeactivateGuard implements CanDeactivate<MyComponent> {
  canDeactivate(component: MyComponent) {
    return (() => component.canDeactivate())();
  }
}

【讨论】:

  • 谢谢丹尼尔,成功了。我现在可以看到模态窗口弹出窗口。但是,如果我现在单击它上面的任何按钮,我会收到错误:无法读取未定义的属性“closeRow”。我认为 Angular 显示了模态并失去了范围。我需要以某种方式使范围保持最新并获取用户输入的结果,然后将该结果提交到 .有什么想法吗?
  • closeRow 属性在哪里定义和使用?我在这里的任何地方都看不到它。我很想有一个 plunker,所以我可以自己测试它......
【解决方案2】:

我不确定 Kendo 是如何工作的,但是当仅使用 confirm() 时,您会像这样在 canDeactivate() 函数中返回该函数:

canDeactivate() {
  return confirm("Are you sure you want to navigate away?");
}

您可以阅读有关 canDeactivate() here 的更多信息。

【讨论】:

  • 这已经可以了,但我想要一些比简单的确认对话框更有风格和定制的东西。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-21
  • 1970-01-01
  • 2021-11-26
  • 1970-01-01
  • 1970-01-01
  • 2022-11-03
相关资源
最近更新 更多