Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to trigger function from one component to another in angular2?

Tags:

angular

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?

like image 871
Rolando Avatar asked Oct 28 '16 22:10

Rolando


2 Answers

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:

  • Getting Started on Subjects
like image 193
Paul Samsotha Avatar answered Oct 14 '22 21:10

Paul Samsotha


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

like image 39
Kshitij Avatar answered Oct 14 '22 20:10

Kshitij