'Angular 6, fire an event on the component that is not current route
I am developing an angular 6 SPA-based application, considering there are two routes A & B, in route B which uses component B, there is a button to open the modal window. now on route A which uses component A, I would like to open the same modal window? first, would that be possible?
I have created a common component communication service as below and injected it into component B, but apparently, that is not working.
export class ComponentCommunicationService {
private open= new Subject();
public openModal$ = this.open.asObservable();
open() {
this.open.next(true);
}
}
Solution 1:[1]
I usually do this for common modals (input modal/confirmation modal) using a PresentationService. So anyone in the app that wants to show a confirmation dialog, just imports the service and calls service.confirm() and gets back an Observable that completes with the result.
https://stackblitz.com/edit/andreit-note-taker?file=src%2Fapp%2Fservices%2Fpresentation.service.ts
import { Injectable, ApplicationRef, ComponentFactoryResolver, Injector } from '@angular/core';
import { Observable } from 'rxjs';
import { first, switchMap } from 'rxjs/operators';
import { ConfirmationDialogComponent } from '../components/confirmation-dialog/confirmation-dialog.component';
@Injectable()
export class PresentationService {
constructor(
private componentFactoryResolver: ComponentFactoryResolver,
private injector: Injector,
private appRef: ApplicationRef,
) {
}
show<T>(component: Type<T>, options) {
return new Observable<T>((observer) => {
const injector = Injector.create(
Object.keys(options).map(key => ({
provide: key,
useValue: options[key],
})), this.injector
);
const componentRef = this.componentFactoryResolver
.resolveComponentFactory(component)
.create(injector);
this.appRef.attachView(componentRef.hostView);
document.body.appendChild(componentRef.location.nativeElement);
observer.next(componentRef.instance);
return () => {
this.appRef.detachView(componentRef.hostView);
componentRef.destroy();
};
});
}
confirm({ title, message }) {
return this.show(ConfirmationDialogComponent, { title, message })
.pipe(
switchMap(v => v.confirm$),
first(),
);
}
}
interface Type<T> extends Function {
new(...args: any[]): T;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Andrei Tătar |
