Angular: invoking a function in one component, with events on another component

Maoration picture Maoration · Sep 19, 2018 · Viewed 11.9k times · Source

Working with Angular6, let's say I have 2 child components A, B that are both part of parent component P. I want to use a form input on component A- so once clicked, the string value will pass and trigger a function on component B. something like this perhaps:

functionOnB(valueFromA: string) { //some code here; } 

is this even possible?

I've successfully transmitted data between components using angular's EventEmitter, but is it possible to invoke functions with this data, not just pass the raw information?

Answer

Learning picture Learning · Sep 19, 2018

A common service can be used to trigger the event/function from another component. For example: ComponentA's click event will call a service method. Then, that service method should emit another event. ComponentB should then subscribe to the service's event emitter. Sample code: ChildA (HTML):

<button (click)="onClick()"></button>

ChildA Controller (TS):

  onClick() {
    this.commonService.AClicked('Component A is clicked!!');
  }

Common Service (TS):

import { Injectable, EventEmitter, Output } from '@angular/core';

@Output() aClickedEvent = new EventEmitter<string>();

AClicked(msg: string) {
  this.aClickedEvent.emit(msg);
}

ChildB Controller (TS):

  ngOnInit() {
    this.commonService.aClickedEvent
    .subscribe((data:string) => {
      console.log('Event message from Component A: ' + data);
    });
  }