I\'m trying to use the routerCanDeactivate
function for a component in my app. The simple way to use it is as follows:
routerCanDeactivate() {
Here is a technique that worked for me. It is pretty similar to @iliacholy's answer, but uses a modal component instead of a jQuery modal. This makes it a somewhat more "Angular 2" approach. I believe it's still relevant to your question.
First, build an Angular Component for the modal:
import {Component, Output, EventEmitter} from '@angular/core;
@Component({
selector: 'myModal',
template: `
`
})
export class MyModal{
private hideModal: boolean = true;
@Output() buttonResultEmitter = new EventEmitter();
constructor(){}
openModal(){
this.hideModal = false;
}
closeModal(){
this.hideModal = true;
}
clickedYes(){
this.buttonResultEmitter.emit(true);
}
clickedNo(){
this.buttonResultEmitter.emit(false);
}
}
Then on your component with RouterCanDeactivate(), import and reference the MyModal instance:
import {MyModal} from './myModal';
@Component({
....
directives: [MyModal]
})
and in the class code:
private myModal: MyModal;
Create a method returning a promise, which is subscribed to the eventEmitter on myModal:
userClick(): Promise {
var prom: new Promise((resolve, reject) => {
this.myModal.buttonResultEmitter.subscribe(
(result) => {
if (result == true){
resolve(true);
} else {
reject(false);
}
});
});
return prom;
}
and finally, in the RouterCanDeactivate hook:
routerCanDeactivate(next: ComponentInstruction, prev: ComponentInstruction) {
this.myModal.openModal();
return this.userClick().catch( function(){return false;} );
}
As @drewmoore mentioned, using Observables is preferred in Angular 2, but A) that wasn't your question, and B) The routerCanDeactivate hook resolves to boolean | Promise, so this approach seemed more natural to me.