Reputation: 25
I am new to Angular. I have two components and when component A has clicked the component 2 should show (add a class). If it is a parent child component I can do it by calling a template reference variable. But in this case, it is not. They are siblings. I've tried many places but they only showed communicating data. What is the best method for this?
Comp-A HTML
<app-comp-a>
<button (click)="profilePanel.panelOpen()"></button>
<app-comp-a>
Comp-B HTML
<app-comp-b #profilePanel>
<div *ngClass="panelCss">
<p>panel opened</p>
</div>
<app-comp-b>
Comp-B TS
panelCss = 'hidePanel';
panelOpen(){
panelCSS = 'showPanel';
}
Upvotes: 1
Views: 2573
Reputation: 1784
All you need is a service where you have a variable of type Subject
. With this variable you will be able, in your component B, to wait for component A to send something.
service.ts
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';
@Injectable()
export class SiblingServiceService {
showSibling = new Subject<boolean>();
constructor() { }
}
showSibling
is your Subject where you can wait for data in component B
component A
import { theService } from 'path/to/service'
...
export class SiblingAComponent implements OnInit {
constructor(private service: theService) { }
ngOnInit() {
}
openPanel(){
this.service.showSibling.next(true);
}
}
component B
import { theService } from 'path/to/service'
...
export class SiblingBComponent implements OnInit {
active: boolean = false;
constructor(private service: theService) { }
ngOnInit() {
}
openPanel(){
this.service.showSibling.subscribe(res => {
this.active = res
});
}
}
Here a stackblitz working example
Upvotes: 2