首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用提交按钮时不使用CanDeactivate保护

使用提交按钮时不使用CanDeactivate保护
EN

Stack Overflow用户
提问于 2017-03-18 12:47:05
回答 4查看 5K关注 0票数 6

这是我的canDeactivate卫士,它可以工作。但是当我使用提交按钮时,我不想叫保安。只有当我通过任何其他方式导航时。多么?

代码语言:javascript
复制
import { Injectable } from '@angular/core';
import { Router, CanDeactivate } from '@angular/router';
import { FormGroup } from '@angular/forms';

export interface FormComponent {
    myForm: FormGroup;
}

@Injectable()
export class DirtyGuard implements CanDeactivate<FormComponent>  {
  constructor(private router: Router) {}

  canDeactivate(component: FormComponent) {
      console.log(component.myForm)
        if (component.myForm.dirty ){
            return confirm('You have unsaved changes. Are you sure you want to navigate away?');
        }
        return true;
  }
}

 <button md-raised-button [disabled]="!myForm.valid" type="submit" color="primary">
                            <i class="material-icons">arrow_forward</i>
                            Exposures: Currencies
                        </button>
EN

回答 4

Stack Overflow用户

发布于 2017-06-30 01:50:39

angular v.4 -未在v.2上测试,但应该可以在上工作

卫兵'canDeactivate‘被正确调用,但是你只想为你提交的场景返回true,那么我们如何确定呢?您已经有了FormGroup的句柄,但是这似乎没有与submitted相关的属性。作为另一种选择,您可以在组件类中使用@ViewChild装饰器来获得窗体的句柄,如下所示:

代码语言:javascript
复制
@ViewChild('myForm') myForm;

为了让它起作用,你必须为你的表单添加一个局部变量,如下所示:

代码语言:javascript
复制
<form #myForm="ngForm" (ngSubmit)="onSubmit()">

然后,您将在myForm对象上看到一个名为_submitted的属性。这允许您更新if条件,以便只在脏&&!提交时显示确认消息。例如:

代码语言:javascript
复制
if (this.myForm.form.dirty && !this.myForm._submitted ){
    return confirm('You have unsaved changes. Are you sure you want to navigate away?');
}
return true;

根据发布的日期,我假设你已经解决了这个问题,但这至少可以解释发生了什么。

票数 3
EN

Stack Overflow用户

发布于 2019-03-05 20:56:05

在我们的组件中,我们可以根据需要使用canDeactivate方法来欺骗警报。

组件:

代码语言:javascript
复制
import { ComponentCanDeactivate } from './pending-changes.guard';
import { HostListener } from '@angular/core';
import { Observable } from 'rxjs/Observable';

export class MyComponent implements ComponentCanDeactivate {
 @ViewChild('RegisterForm')
 form: NgForm;

  // @HostListener allows us to also guard against browser refresh, close, etc.
  @HostListener('window:beforeunload')
  canDeactivate(): Observable<boolean> | boolean {
    // insert logic to check if there are pending changes here;
    // returning true will navigate without confirmation
    // returning false will show a confirm dialog before navigating away
    return this.form.submitted || !this.form.dirty; // insert your code here for submit event 

  }
}

防护:

代码语言:javascript
复制
import { CanDeactivate } from '@angular/router';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';

export interface ComponentCanDeactivate {
  canDeactivate: () => boolean | Observable<boolean>;
}

@Injectable()
export class PendingChangesGuard implements CanDeactivate<ComponentCanDeactivate> {
  canDeactivate(component: ComponentCanDeactivate): boolean | Observable<boolean> {
    // if there are no pending changes, just allow deactivation; else confirm first
    return component.canDeactivate() ?
      true :
      // NOTE: this warning message will only be shown when navigating elsewhere within your angular app;
      // when navigating away from your angular app, the browser will show a generic warning message
      // see https://stackoverflow.com/questions/52044306/how-to-add-candeactivate-functionality-in-component
      confirm('WARNING: You have unsaved changes. Press Cancel to go back and save these changes, or OK to lose these changes.');
  }
}

路由:

代码语言:javascript
复制
import { PendingChangesGuard } from './pending-changes.guard';
import { MyComponent } from './my.component';
import { Routes } from '@angular/router';

export const MY_ROUTES: Routes = [
  { path: '', component: MyComponent, canDeactivate: [PendingChangesGuard] },
];

模块:

代码语言:javascript
复制
import { PendingChangesGuard } from './pending-changes.guard';
import { NgModule } from '@angular/core';

@NgModule({
  // ...
  providers: [PendingChangesGuard],
  // ...
})
export class AppModule {}
票数 1
EN

Stack Overflow用户

发布于 2019-06-25 03:31:01

我假设您是在用户点击submit按钮之后导航离开的。在表单有效时禁用can禁用保护的问题是,用户可能会在表单完全填写后意外地点击取消/后退按钮等,从而丢失所有工作。换句话说,表单有效并不意味着您想要停用can-deactivate防护。

如果您正在导航,您可以在路由导航之前在onSubmit函数中将属性设置为"true“,并在您的守卫逻辑中使用它。

Component (反应式表单)

代码语言:javascript
复制
export class MyComponent {

// ..

submitSuccess: boolean;

canDeactivate(): boolean | Observable<boolean> | Promise<boolean> {
   if (!this.inputForm.dirty || this.submitSuccess ) {
    return true;
  }
return this.confirmDialogService.confirm('Discard changes?');
}

// ...
  onSubmit() {
    this.submitSuccess = true; 
    this.router.navigate(['my-page']);
  }
}

确认对话框服务

代码语言:javascript
复制
import { Injectable } from '@angular/core';
import { Observable, of } from 'rxjs';

@Injectable({
providedIn: 'root'
})
export class ConfirmationDialogService {
/**
* Ask user to confirm an action. `message` explains the action and choices.
* Returns observable resolving to `true`=confirm or `false`=cancel
*/
 confirm(message?: string): Observable<boolean> {
 const confirmation = window.confirm(message || 'Are you sure? Your changes 
 will be lost.');

return of(confirmation);
 }
}

可以停用防护

代码语言:javascript
复制
export interface CanComponentDeactivate {
canDeactivate: () => Observable<boolean> | Promise<boolean> | boolean;
}
@Injectable({
  providedIn: 'root',
})
export class CanDeactivateGuard implements 
CanDeactivate<CanComponentDeactivate> {
  canDeactivate(component: CanComponentDeactivate) {
    return component.canDeactivate ? component.canDeactivate() : true;
   }
}

路由

代码语言:javascript
复制
\\ ...
children: [
  { path: 'my-path', component: MyComponent, canDeactivate: 
[CanDeactivateGuard] },

]},

// ..

希望它能帮上忙!

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42870564

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档