3

Am working on an angular application, i need to show an alert message if the user leaves the page with unsaved changes while editing.

i have created and registered a candeactivate guard in routes for this which is working fine in parent component. But not working in child component .How to solve this?

{
    path: 'create',
    component: CreateComponent,
    canDeactivate: [ConfirmationGuard],
},
{
    path: ':id',
    component: ViewUserComponent,
    children: [
        {
            path: ':id',
            component: AddressComponent,
            canDeactivate: [ConfirmationGuard],
        },
    ],
    canDeactivate: [ConfirmationGuard],
},

'create' is working good, but the addresscomponent is not working as it is a child component!

confirmationguard.ts:-

import { Component } from '@angular/core';
import { CanDeactivate } from '@angular/router';
import { ConfirmLeaving } from './interface';

 export declare class ConfirmationGuard implements 
 CanDeactivate<ConfirmLeaving | Component> {

 canDeactivate(component: ConfirmLeaving | Component): Promise<boolean>;
 }
mevr
  • 1,075
  • 3
  • 14
  • 32

2 Answers2

1

ConfirmationGuard needs to be an actual service... in other words, it must be @Injectable, and provided in a module (or you can use providedIn: root).

0

If AddressComponent have a module, you can import its own module in @NgModule under imports section to making sure you will have imports all of its imports, declarations or provider