Reputation: 121
I am having a parent component. Let say; Component1. In its html I have added below code.
<div>
<router-outlet></router-outlet>
</div>
<div>
<button>Banner</button>
</div>
I want to pass 'Banner' button click functionality into another component which will be rendering through router-outlet. After fetching button click functionality, I want to open a popup inside that component. In routing module, I have added path like below:
{
path: "parent",
component: Component1,
},
children: [
{
path: 'child',
loadChildren:
() => import('path').then(m => m.Module2)
}]
Inside this Module2 I am having another root component Component2. In its html I have added the listening component selector.
Component2 html:
<app-component3></app-component3>
In Component3 ts file only I want to get Banner clicks functionality. And while listening to that I want to open popup. If anyone could assist, it would be helpful.
Upvotes: 1
Views: 25
Reputation: 77
This may help:
// banner.service.ts
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class BannerService {
private clickSubject = new Subject<void>();
click$ = this.clickSubject.asObservable();
emitClick() {
this.clickSubject.next();
}
}
This service creates a Subject to emit click events and an Observable for components to subscribe to.
// component1.component.ts
@Component({...})
export class Component1 {
constructor(private bannerService: BannerService) {}
onBannerClick() {
this.bannerService.emitClick();
}
}
<!-- component1.component.html -->
<button (click)="onBannerClick()">Banner</button>
This component calls the service to emit a click event when the button is clicked.
// component3.component.ts
@Component({...})
export class Component3 implements OnInit, OnDestroy {
private subscription: Subscription;
constructor(private bannerService: BannerService) {}
ngOnInit() {
this.subscription = this.bannerService.click$.subscribe(() => {
this.openPopup();
});
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
openPopup() {
console.log('Opening popup');
// Popup logic here
}
}
This component subscribes to the click events and opens a popup when a click is received.
This solution allows the banner click in Component1 to trigger an action in Component3, even when they're not directly related in the component tree.
Upvotes: 1
Reputation: 58657
My understanding is that you want to communicate between two components that are separated by routing, the solution for this is to use an event bus, where we emit an event using a subject in component a and then receive the event in component c.
Upvotes: 0