我的问题是我有一个父级组件和父级组件的许多子级组件。父级组件没有任何形式,子级组件也有表单。所有子级组件都共享父级组件和子级组件相同的路由没有任何路由器链接可唯一标识。因此,任务是在表单变脏且用户离开该页面时显示弹出窗口。因此,我实现了可停用的防护功能。因此在“ app.module.ts”中我可以为子组件提供can-deactivate(bcz子组件没有任何路由器路径)。 我该如何实现?
有人可以帮我吗?过去两天的苦苦挣扎:( 任何其他解决方案也可以 提前Hugeee thanx
can-deactivate-guard.ts:
import {ComponentCanDeactivate} from './component-can-deactivate';
@Injectable()
export class CanDeactivateGuard implements CanDeactivate<ComponentCanDeactivate> {
canDeactivate(component: ComponentCanDeactivate): boolean {
if(!component.canDeactivate()){
if (confirm("You have unsaved changes! If you leave, your changes will be lost.")) {
return true;
} else {
return false;
}
}
return true;
}
}
component-can-deactivate.ts:
export abstract class ComponentCanDeactivate {
abstract canDeactivate(): boolean;
@HostListener('window:beforeunload', ['$event'])
unloadNotification($event: any) {
if (!this.canDeactivate()) {
$event.returnValue =true;
}
}
}
form-can-deactivate.ts:
export abstract class FormCanDeactivate extends ComponentCanDeactivate{
abstract get form():NgForm;
canDeactivate():boolean{
return this.form.submitted || !this.form.dirty
}
}
parent component.html:ParentComponent.html中没有表格
<child1>some actions</child1>
<child2>some actions</child2>
,依此类推 child1.component.html:
<form #form="ngForm">some fields</form>
app-routing.module.ts:
routes={path:':parent/somepath',component:ParentComponent,canDeactivate:[CanDeactivateGuard]}
答案 0 :(得分:0)
如果您是在不更改网址的情况下在容器中加载其他component
,并且需要在导航之前检查表单状态是否为脏,则可以继续使用ngOnDestroy()
。一旦您离开活动组件,就会触发此事件。
如果您需要处理浏览器事件,例如后退/刷新/关闭按钮,则需要添加@HostListener
装饰器