加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

如何使用angular2材质对话框阻止canDeactivate

发布时间:2020-12-17 10:19:10 所属栏目:安全 来源:网络整理
导读:如果用户从具有脏表单的页面导航,我成功使用canDeactivate提供警告消息: 我正在使用的代码在这里: is_submit = false; canDeactivate() { //https://scotch.io/courses/routing-angular-2-applications/candeactivate if (this.myForm.dirty == true this.
如果用户从具有脏表单的页面导航,我成功使用canDeactivate提供警告消息:

我正在使用的代码在这里:

is_submit = false;
   canDeactivate() {
       //https://scotch.io/courses/routing-angular-2-applications/candeactivate
        if (this.myForm.dirty == true && this.is_submit==false){
            return window.confirm('Discard changes?');
        } //end if
        return true
    } // end  canDeactivate

这是我得到代码的地方:

https://scotch.io/courses/routing-angular-2-applications/candeactivate

但是我想使用angular2对话框.这是我的代码:

//ts for the main component

    is_submit = false;
   canDeactivate() {
        if (this.myForm.dirty == true && this.is_submit==false){
            const config = new MdDialogConfig();
            config.disableClose=true;
            let dialogRef = this.dialog.open(DialogCanDeactive,config);
            dialogRef.afterClosed().subscribe(result => {
                if (result=='cancel'){
                    return false;
                } 
                if (result=='save'){
                    return true;
                } 
                if (result=='discard'){
                    return true;
                } 
            }); //end dialogRef
        } //end if
        return true
    }

 ///Code for the dialog

@Component({
  selector: 'can_deactive_dialog',template: `
<div>
    <button md-raised-button (click)="dialogRef.close('cancel')">Cancel</button>
    <button md-raised-button (click)="dialogRef.close('save')">Save Changes</button>
    <button md-raised-button (click)="dialogRef.close('discard')">Discard Changes</button>
</div>
`,})
export class DialogCanDeactive {


  constructor(public dialogRef: MdDialogRef<DialogCanDeactive>) {} //end constructor

}

当我离开时会发生什么:

1)我转到导航页面

2)然后对话显示..

如何使用以下代码的Dialog块?

window.confirm('Discard changes?')
canDeactivate方法也可以返回Promise或Observable.您应该返回该值并解析promise或使用您想要的结果在observable上发出值.

在您的具体示例中,您可以从afterClosed方法返回observable而不是订阅它,并将其映射到布尔值:

return dialogRef.afterClosed().map(result => {
                if (result=='cancel'){
                    return false;
                } 
                if (result=='save'){
                    return true;
                } 
                if (result=='discard'){
                    return true;
                } 
            }).first();

另外,我会从保护中移出这个逻辑,例如在组件中,然后从那里调用一个方法.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读