Reputation: 2116
I have two child components on a parent component. I am trying to pass a click event or more specifically to check when a button is clicked in one of the child components and pass that to the other child component.
Parent
<app-connect-advice [memberDetails] = "memberDetails"></app-connect-advice>
<app-help-tips subtext="Before we show you your savings"></app-help-tips>
Connect-advice-component(child-1)
<div (click)="showConnectWindow = true">
<div>CONNECT</div>
</div>
Help-tips-component(child-2)
<div class="float-right pb-4 arrow-box">
<svg fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="0.9" viewBox="0 0 24 24"><path _ngcontent-yhk-c5="" d="M6 18L18 6M6 6l12 12"></path></svg>
</div>
So essentially what I want to do is if the user clicks on the showConnectWindow
click event, then I want to inform the Help-tips-component
that this has happened. My end goal is to apply styles based on when the click event is clicked or not.
Any idea what I can do here?
Upvotes: 1
Views: 1631
Reputation: 14892
You can use Subject(RXJS)
1- Create a service
export class InformService {
private informSource = new Subject();
informStatus$ = this.informSource.asObservable();
public warnToTipComponent() {
this.informSource.next();
}
}
2-
export class AppConnectAdviceComponent{
constructor(
....
private informService: InformService) { }
public showContent(){
showConnectWindow = true;
informService.warnToTipComponent();
}
}
in the app-connect-advice-component.html:
<div (click)="showContent()">
<div>CONNECT</div>
</div>
3- Here, we have to subscribe to informStatus$
to notice when the user click on showContent()
export class AppHelpTipsComponent implements OnInit , OnDestroy {
public subscription: Subscription;
constructor(
....
private informService: InformService) { }
ngOnInit() {
this.subscription= this.informService.informStatus$.subscribe(_ => {
// Here, you will notice
})
}
ngOnDestroy(): void {
if (this.subscription)
this.subscription.unsubscribe();
}
}
ngOnDestroy(): void {
if (this.subscription)
this.subscription.unsubscribe();
}
Upvotes: 2
Reputation: 1227
Basically there are two common solutions to your problem. The first approach would be for the child component to emit an event to the parent when the click event is triggered and the parent informs the other child. The limitation here is that this event can only be passed to the parent component and not to other components. Check out this article.
The other possibility would be to create a service that allows you to interact with all the components you want. Have a look at this article for a better overview.
Upvotes: 0