Home > database >  Angular - onClick trigger menu on another component
Angular - onClick trigger menu on another component

Time:06-14

I have created two components. The first one contains a button and the second a dropdown menu. When the user clicks on this button (on the first component) I want to display the menu (on the second component).

Is it possible (and how?) to "call" the menu from the component where the button is or should I merge them in the same component?

Thanks in advance.

CodePudding user response:

Yes, it is possible, you can make use of BehaviorSubject from rxjs.

Create a service file, e.g custom.service.ts:

buttonClickSubject: Subject<Boolean> = new BehaviorSubject(null);

buttonClick$: Observable<Boolean> = this.buttonClickSubject.asObservable();

Comp A (on button click, call next() of Subject):

 this.service.buttonClickSubject.next(true);

Comp B (inside constructor subscribe to the Observable):

this.service.buttonClick.subscribe(data => {
  //write you menu code here
});

Answer to your 2nd Question :

Its completely depends on your design. If your Menu Component is large enough and you can resue in diff places, then you can definitely create a new Component else no need.

  • Related