How to apply a canDeactive guard to every route while lazy loading routes

Discussão em 'Angular' iniciado por Tim Bunk, Abril 17, 2025.

  1. Tim Bunk

    Tim Bunk Guest

    In my Angular applications I work with modals and when a modal is open and the user is trying to navigate using the back or forward button of the browser then this action is disabled if a modal is open. I created a canDeactiveGuard to achieve this effect.

    Now I want to apply this guard to every route in my project and my routes are lazy loaded. How can I achieve this without adding the guard manually to every route?

    @Injectable({
    providedIn: 'root',
    })
    export class CanDeactivateGuard implements CanDeactivate<unknown> {

    constructor(
    private modalService: ModalService,
    private router: Router,
    ) { }

    canDeactivate(): boolean {
    if (this.modalService.getModalsCount() > 0) {
    return false;
    }
    return true;
    }
    }

    Continue reading...

Compartilhe esta Página