12

I have two components componentA and componentB. Both of them are sibblings, and are children of componentMother.

I want to make it such that when I click on a button on componentA, it triggers a function call on componentB.

Is the way to do this using a service with an observable and having componentA emit events that componentB subscribes to or is there a better/best practice way?

Rolando
  • 51,528
  • 92
  • 250
  • 377
  • That, or emit an event from an output in A, to which the parent component subscribes and sets an input or calls a method on B. – JB Nizet Oct 28 '16 at 22:20
  • 1
    check out http://stackoverflow.com/questions/39132385/communicate-between-sibling-components-anguar-2/39132530#39132530. it should answer your question – kit Oct 28 '16 at 22:25
  • I would do a local small service, it's the cleanest way. – tibbus Oct 28 '16 at 22:28
  • @tibbus Could you show a basic example of how these components would be connected to the service? – Rolando Oct 28 '16 at 22:29
  • @kit Why you don't post the answer (with the source and adaptations) here? – William Ardila Jul 04 '17 at 20:14
  • 1
    because I've already answered it in provided link. I don't like to duplicate stuff. – kit Jul 04 '17 at 20:19

2 Answers2

17

I would probably use a service that uses a Subject. This way it can be both published to and subscribed from

import { Subject } from 'rxjs/Subject';

class SomeService {
  private _subject = new Subject<any>();

  newEvent(event) {
    this._subject.next(event);
  }

  get events$ () {
    return this._subject.asObservable();
  }
}

The from your components, one can publish and one can subscribe

@NgModule({
  providers: [ SomeService ]
})
class AppModule {}

@Component()
class ComponentOne {
  constructor(private service: SomeService) {}

  onClick() {
    service.newEvent('clicked!');
  }
}

@Component()
class ComponentTwo {
  constructor(private service: SomeService) {}

  ngOnInit() {
    this.service.events$.forEach(event => console.log(event));
  }
}

See also:

cs95
  • 330,695
  • 80
  • 606
  • 657
Paul Samsotha
  • 197,959
  • 33
  • 457
  • 689
1

Use RxJS SUBJECT (~EventEmitter):import { Subject } from 'rxjs/Subject';

Subject service will allow you to enable bi-directional communication for a parent component and its children.

Reference : https://angular.io/guide/component-interaction#parent-and-children-communicate-via-a-service

For more details of

RxJs SUBJECT

check this one : https://www.youtube.com/watch?v=rdK92pf3abs

Kshitij
  • 595
  • 9
  • 17