我的Angular4页面中有两个标签(PrimeNg Tabview),其中包含许多输入字段,例如文本框, textareas ,下拉列表等我还有一个侧面菜单栏,可以导航到应用程序中的其他页面。我想如果这些输入字段中的数据有任何更改,那么如果用户尝试更改选项卡,或者使用侧面导航到其他页面,则会出现弹出消息(模式或确认框)菜单栏。
我尝试了ngOnDestroy()
方法。虽然此方法仅在页面关闭时触发(通过导航到其他页面或移动到下一个选项卡页面)但是它不允许您在方法中显示模态/确认框,因为它在销毁生命周期钩子上
请帮助我确定实际的事件,如果页面/表单中的任何输入字段中有更改,我可以使用确认框提示用户。
@surjit建议:
我-guard.service.ts :
export interface CanComponentDeactivate {
CanDeactivate: () => Observable<boolean> | Promise<boolean> | boolean;
}
@Injectable()
export class CreateRequestGuardService implements CanDeactivate<CanComponentDeactivate> {
canDeactivate(component: CanComponentDeactivate) {
let vDeactivate = component.CanDeactivate ? component.CanDeactivate() : true;
return vDeactivate;
}
}
在 my-component.ts :
内import { CreateRequestGuardService } from './my-guard.service';
canDeactivate(): Observable<boolean> | boolean {
console.log('I am moving away!');
if (!this.isSaved) {
const confirmation = window.confirm('Are you sure?');
return Observable.of(confirmation);
}
else{
return true;
}
}
在 my-router.ts :
中import { CreateRequestGuardService } from './my-guard.service';
const allRoutes: Routes = [
{ path: 'save', component: my-component, canDeactivate: [MyGuardService]},
{ path ....},
..
]
答案 0 :(得分:2)
在要保护的组件路径中使用CanDeactivate
防护
阅读CanDeactivate了解更多信息
我-guard.service.ts:强>
export interface CanComponentDeactivate {
CanDeactivate: () => Observable<boolean> | Promise<boolean> | boolean;
}
@Injectable()
export class CreateRequestGuardService implements CanDeactivate<CanComponentDeactivate> {
canDeactivate(component: CanComponentDeactivate,
currentRoute: ActivatedRouteSnapshot,
currentState: RouterStateSnapshot,
nextState?: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
return component.canDeactivate(); //the function will be called on the component, that's why we'll implement the function on the component.
}
}
我-router.ts:强>
import { CreateRequestGuardService } from './my-guard.service'; //the class name in my-guard.service.ts
const allRoutes: Routes = [
{ path: 'save', component: myComponent, canDeactivate: [CreateRequestGuardService]},
{ path ....},
..
]
我-component.ts 强>
import { CreateRequestGuardService } from './my-guard.service';
export class myComponent implements CanComponentDeactivate { //implements the interface created on the guard service
/*
your component data
*/
//implementation of canDeactivate
canDeactivate(): Observable<boolean> | Promise<boolean> | boolean {
if(form_is_edited && not_saved){
return confirm("Discard Changes?");
}
else
return true;
}
}
注意:也不要忘记将保护服务(类)添加到providers
文件中的app.module.ts
数组。