I\'m trying to use the routerCanDeactivate
function for a component in my app. The simple way to use it is as follows:
routerCanDeactivate() {
Since everyone is talking about Observables, I figured that I would take a look and build upon @petryuno1's answer.
Starting with his ModalComponent
:
import {Component, Output, ViewChild} from '@angular/core;
@Component({
selector: 'myModal',
template: `
`
})
export class MyModal{
private hideModal: boolean = true;
private clickStream = new Subject();
@Output() observable = this.clickStream.asObservable();
constructor(){}
openModal(){
this.hideModal = false;
}
closeModal(){
this.hideModal = true;
}
clickedYes(){
this.clickStream.next(true);
}
clickedNo(){
this.clickStream.next(false);
}
}
Next, we go to the AppComponent
:
import { Component, ViewChild} from '@angular/core';
import {MyModal} from './myModal';
import {Subscription} from "rxjs";
@Component({
....
directives: [MyModal]
})
export class AppComponent {
@ViewChild(ConfirmModal) confirmModal: ConfirmModal;
constructor(){...};
public showModal(){
this.myModal.openModal();
this.subscription = this.myModal.observable.subscribe(x => {
console.log('observable called ' + x)
// unsubscribe is necessary such that the observable doesn't keep racking up listeners
this.subscription.unsubscribe();
});
}
}
The elegance of observables is that we now get to write a lot less code to do the same thing.