How to call a function from one component to another in angular2?

I have two components componentA and componentB. Both are siblings and are children of componentMother.

I want to make it so that when I press a button on component A, it calls a function call in component B.

Is there a way to do this using a service with an observable and having events generating component A that component B signs or is there a better / better way?

+5
source share
3 answers

I would probably use a service that uses Subject . Thus, it can be published and subscribed to

 import { Subject } from 'rxjs/Subject'; class SomeService { private _subject = new Subject<any>(); newEvent(event) { this._subject.next(event); } get events$ () { return this._subject.asObservable(); } } 

From your components you can publish and subscribe

 @NgModul({ 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:

+6
source

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

The theme service allows you to enable bi-directional communication for the parent component and its children.

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

Read more about

RxJs SUBJECT

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

+2
source

You would use the service and subscribe to it. Read the chapter on component interactions on the Angular website:

https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service

0
source

Source: https://habr.com/ru/post/1258962/


All Articles