Search code examples
angularbooleancomponents

Angular 2 - pass boolean "true" from one component to another (not siblings)


On one component I have button that triggers function:

<button (click)="open Popup(); hideButton()"></button>

I have, lets say: buttonService that I should use for connection between these two components.

And in second component (which is not parent-child related to first component) I have multiple buttons like this:

<button class="element1"></button>
<button [class.hiddenClass]="hideButt" class="element2"></button>
<button class="element3"></button>

Second component is popup that is opening on same button click from first component and at that moment it should also trigger hideButton() function to pass boolean "true" to hideButt and hide button on that second (popup) component. How can i do it? With subscribe, Observable, EventEmitter?


Solution

  • You might find the rxjs subject useful. It's great for cross-component communication with a service. Add a property in your service class:

    public buttonClick = new Subject<boolean>()
    

    Then in the component you want to send the data out from, reach out to the service and call next () on it

    this.myservice.buttonClick.next (true)
    

    Then you can subscribe to your subject from any other component

    this.myservice.buttonClick.subscribe (data => data)
    

    And whenever you call next, any subscriptions will receive your new data from any component.

    Also, a behavior subject is a subject that will emit an initial value

    Hope this helps!