Scenario:
Tech: Angular version 5 app using typescript and webpack.
I Have made a canDeactivate guard to see if a users wants to leave the current route.
When the user tries to navigate to another route a custom modal needs to appear that I've shown.
Then the user clicks yes in the modal (e.g. I want to navigate away).
Problem:
My guard service get hit fine but the modal method "canDeactivate" doesnt get hit. Therefore the modal doesnt open.
I've added the custom modal component to the html.
I've added the guard and the modal to the app module fine.
These are my files below
DeactivateGuardService:
import { ActivatedRouteSnapshot, CanDeactivate, RouterStateSnapshot } from '@angular/router';
import { Injectable } from '@angular/core';
import { DeactivateModalComponent } from '../shared/modals/deactivate-modal/deactivate-modal.component';
@Injectable()
export class DeactivateGuardService implements CanDeactivate<DeactivateModalComponent> {
canDeactivate(component: DeactivateModalComponent) {
console.log('DeactivateGuardService');
// Note: I need this canDeactivate to call it inside my modal.
let canUse = component.canDeactivate();
return canUse;
}
}
My custom modal:
import { Component, EventEmitter, Output, Input, HostListener } from '@angular/core';
@Component({
selector: 'deactivate-modal',
templateUrl: 'deactivate-modal.component.html',
styleUrls: [
'../../../managed-app/managed-app.component.scss',
'../../../managed-app/shared/app-flow-styles.scss',
'deactivate-modal.component.scss',
]
})
export class DeactivateModalComponent {
public isModalVisible: boolean = false;
public isRouteActive: boolean = false;
constructor() {}
// Note: this is not getting hit - when I need it too.
canDeactivate() {
this.isModalVisible = true;
return this.isRouteActive;
}
public toggleModal(isVisible: boolean): void {
this.isModalVisible = isVisible;
}
public redirectUser(): void {
this.isRouteActive = true;
}
Route with canDeactivate set:
{
path: 'createJob',
component: testComponent,
canDeactivate: [ DeactivateGuardService ],
},