我在Angular4页面中有两个选项卡(PrimeNg Tabview),其中包含许多输入字段,例如文本框,textareas,下拉列表等。我还有一个侧边菜单栏,可导航到应用程序内的其他页面。我想要如果这些输入字段中的数据有任何更改,那么如果用户尝试更改选项卡或使用侧面导航到其他页面,那么将出现一个弹出消息(模式或确认框)菜单栏。
我已经尝试过该ngOnDestroy()
方法。尽管仅在关闭页面时(通过导航到其他页面或移至下一个选项卡页面)才会触发此方法,但是由于该方法处于销毁生命周期挂钩上,因此它不允许您从方法内部显示模式/确认框。
如果页面/表单的任何输入字段中都有更改,请帮助我确定实际事件,通过该事件我可以在确认框中提示用户。
@surjit建议:
my-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 ....},
..
]
CanDeactivate
在要保护的组件路径中使用防护
阅读CanDeactivate以获得更多信息
my-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.
}
}
my-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
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句