Reputation: 325
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?
Upvotes: 2
Views: 12863
Reputation: 76
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!
Upvotes: 6
Reputation: 730
I think that you can reach that using eventEmitter, it will notify your second component as soon as you click the button you just need to be subscribe to the event emitter.
Option 1 between components You will do this in the component that you want to trigger the change
Import
import { Injectable, EventEmitter } from '@angular/core';
Declare
@Output()variableEvent: EventEmitter<any> = new EventEmitter();
Set value you want to change
public sendChange(){
this.variableEvent.emit(value);
}
Add this in the template of the component you want to receive the value
<child (sendChange)="getValue($event)"></child>
Add this line in your component.ts
private getValue($event){
//Get the value
}
Option 2 using a service
export class Service {
public change: EventEmitter<any> = new EventEmitter();
public setdata(value) {
this.change.emit(value);
}
}
The component that set the data
export class SetDataComponent {
constructor(private service: Service) {}
private setData(){
this.service.setData(value);
}
}
Component that will receive the data
export class GetDataComponent {
constructor(private service: Service) {}
private getData()
{
this.service.change.subscribe(value => {
let dataRecieve = value;
});
}
}
The advantage of the event emitter is that as soon as the event occurs it will notify all the components that are subscribed.
Upvotes: 4