my understanding of Angular is very basic (I'm trying to learn!) and need some help with regards to setting a click event between 2 separate components. I'll specify the scenario...
I have a header menu which contains a button which on click, will expand and collapse a side menu. The header menu and side menu are separate components. I need to basically toggle a class inside the sidebar component when the button in the header component is clicked
I've read that it might be best to create a service (rxjs/BehaviorSubject) that links the two components together however I've never created one before so not really sure how to proceed.
Is anyone able to assist? Thanks in advance!
As per Software Engineering prospective, identify the problem first, then think of the solution within the scope of design patterns, but also take in consideration the framework. In the mentioned scenario; the Observer Pattern is what you are looking for.
We need to communicate between components that might or might not be located within the same
modulewhich also might have a parent-child or child-parent relationship, or might be brothers-relationship or might not have a relationship at all! So the generic solution is to created aService.Now according to your use case, you're calling it as if you have this one only functionality in which you want to observe this button to toggle the sidenav, but from my own point of view, it's better to create a more generic form of usage in which is defined as "Communication". This will make your service reusable and can do many other things than just observing a button.
I'll add some code to demonstrate.
First of all we've got the
communication.service.tsNow in the
header.component.tsfor example we need to useDIdesign pattern to inject this service and use it tosendData.And in your
sidenav.component.tsAnd we're done!
Now what makes
BehaviorSubjectspecial is that it can be initialized with an initial value (To indicate that sidenav is closed by default for example).You can learn more about
BehaviorSubjecthereHope this helped & Happy coding!