Plunkr: https://plnkr.co/edit/KfPfVSbZm087uIPvFEkM?p=preview
I have developed a service that serves as an API for a modal component. In addition, there is a directive available that can be used to apply a class to any element when the modal is open. However, I am facing an issue where the subscription inside the directive does not trigger no matter what I try.
I attempted using both Subject
and BehaviorSubject
, but neither seems to work.
Service:
@Injectable()
export class ModalApiService {
constructor() {}
private states = new Subject<any>();
states$ = this.states.asObservable();
open(id: string, template?: string): void {
this.states.next({isOpen: true, id: id, template: template});
// This runs as expected
console.log(true);
}
close(id: string): void {
this.states.next({isOpen: false, id: id});
}
}
Directive:
@Directive({
selector: '[modalState]'
})
export class ModalStateDirective implements OnDestroy, OnInit {
constructor(private modalApi: ModalApiService) {}
private modalSubscription: Subscription;
@HostBinding('class.modal-open')
isOpen: boolean;
ngOnInit() {
this.modalSubscription = this.modalApi.states$.subscribe(
state => {
this.isOpen = state.isOpen;
console.log(this.isOpen)
}
);
}
ngOnDestroy() {
this.modalSubscription.unsubscribe();
}
}