要求用户在离开组件之前保存数据

时间:2019-11-26 16:03:30

标签: javascript html angular typescript

我有一个组件父app-sidebar,它可以有两个不同的子组件,具体取决于变量:

<app-content-right *ngIf="!componentService.getEditor.inView"></app-content-right>
        <!-- alternative editors -->
<app-labtech-home *ngIf="componentService.getComponentEditor && componentService.getEditor.inView"></app-labtech-home>

我需要在离开app-labtech-home时用模式通知用户,要求他离开或不保存而无需保存页面。我用

赶上了活动
  @HostListener('document:click', ['$event'])
  clickout(event) {
    if(this.eRef.nativeElement.contains(event.target)) {
      console.log("clicked inside")
    } else {
      if(window.confirm("Are you sure?"))
     alert('Your action here');
    }
  }

app-labtech-home组件内部,但是它退出时没有模式,我需要拦截出口,并且仅在用户接受时才这样做。我该如何实现?谢谢
PS :路线不变,它是同一页面中的不同组件(实际上是一个不同的项目)

我的路由模块:

export const routes: Routes = [
  { path: 'login', component: LoginComponent},
  { path: '', component: HomeComponent, canActivate: [AuthGuard],canDeactivate:[BackButtonDeactiveGuard]}
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

2 个答案:

答案 0 :(得分:0)

我认为您正在寻找: link

答案 1 :(得分:0)

尝试这样:

  • 创建 DeactivateGuardService

.service

import { Injectable } from '@angular/core';
import { CanDeactivate } from '@angular/router';
import { Observable } from 'rxjs/Observable';

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

@Injectable()
export class DeactivateGuardService implements  CanDeactivate<CanComponentDeactivate>{

  canDeactivate(component: CanComponentDeactivate) {
    return component.canDeactivate ? component.canDeactivate() : true;
  }
}
  • 在每个组件路线中添加 canDeactivate 属性

routing.module

@NgModule({
  imports: [
    RouterModule.forRoot([
      { 
        path: 'example', 
        canDeactivate: [DeactivateGuardService],
        component: ExampleComponent 
      }
    ])
  ]
  • 每当用户尝试离开脏页的页面时,调用service方法

.component

export class ExampleComponent {
    loading: boolean = false;
     @ViewChild('exampleForm') exampleForm: NgForm;

     canDeactivate(): Observable<boolean> | boolean {

        if (this.exampleForm.dirty) {

           alert('Discard Unsaved Changes?');
       }
       return true;
     }     

}
相关问题