我有一个组件父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 { }
答案 0 :(得分:0)
我认为您正在寻找: link
答案 1 :(得分:0)
尝试这样:
.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;
}
}
routing.module
@NgModule({
imports: [
RouterModule.forRoot([
{
path: 'example',
canDeactivate: [DeactivateGuardService],
component: ExampleComponent
}
])
]
.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;
}
}