【发布时间】:2019-06-26 03:12:37
【问题描述】:
我的问题是我的父组件有一个父组件和许多子组件。父组件没有任何表单,子组件有表单。所有子组件共享父组件和子组件的相同路由'没有任何路由器链接来唯一标识。所以任务是在表单脏并且用户正在离开该页面时显示弹出窗口。所以我实现了可以停用保护。所以在“app.module.ts”中如何我可以给子组件can-deactivate(bcz子组件没有任何路由器路径)。 我怎样才能做到这一点?
有人可以帮我解决这个问题吗?过去两天一直在挣扎:( 任何其他解决方案也可以 非常感谢提前
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]}
【问题讨论】:
-
如果您添加一些代码示例。帮助您将非常容易。 StackBliz 上的示例
-
好的,我可以给你示例代码
-
您可以编辑您的帖子以获得最佳视图。不要尝试在 cmets 中编写代码
标签: forms angular6 parent-child