我有一个在材质标签中创建的子表单组件:
<md-tab *ngFor="let selectedEntity of selectedEntities; let i=index">
<template md-tab-label>{{selectedEntity.resource.name}}
<i class="fa fa-times" (click)="onTabClose(i)"></i>
</template>
<child-form [entity]="selectedEntity"></child-form>
</md-tab>
我使用ngOnDestroy
显示一个材质对话框,询问用户是否要在关闭标签时进行保存。
ngOnDestroy(): void {
this.promptService.open(this);
};
但是,由于当前状态保存在服务中,因此我不需要在用户更改路径时显示提示,只有当他们关闭选项卡时才会显示。
我是否可以(如果是,如何)检查路由更改是否导致子组件被销毁?
答案 0 :(得分:2)
我在这里设法做的是创建一个布尔属性,在true
事件中设置为NavigationStart
,并在false
事件上设置为NavigationEnd
。这样我只有在路线导航结束时才能打开对话框。以下是我通过几个步骤解决问题的方法:
1.我在inNavigation
prompt.service.ts
的布尔值
2.然后,在服务构造函数中,我订阅了导航事件并相应地设置了inNavigation
:
constructor(private dialog: MdDialog, public router: Router) {
this.router.events.subscribe(event => {
if (event instanceof NavigationStart) {
this.inNavigation = true;
} else if (event instanceof NavigationEnd) {
this.inNavigation = false;
}
});
}
3.然后我使用该布尔属性来检查是否应该打开提示对话框:
public open(entity: any): Observable<boolean> {
if (this.inNavigation == false) {
let dialogRef: MdDialogRef<PromptComponent>;
dialogRef = this.dialog.open(PromptComponent);
dialogRef.componentInstance.entity = entity;
return dialogRef.afterClosed();
}
}
我把所有这些都放在提示服务中,因为我不必改变每一个组件,我仍然可以使用更简单的东西来实现我想要的东西:
ngOnDestroy(): void {
this.promptService.open(this);
}