6

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?

Maor Barazani
  • 680
  • 3
  • 12
  • 31
  • 1
    https://angularfirebase.com/lessons/sharing-data-between-angular-components-four-methods/ if you scroll down there is an example of sharing data with a service. – Jason White Sep 19 '18 at 21:06

2 Answers2

24

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);
    });
  }
Learning
  • 1,333
  • 16
  • 24
2

Yes, it is possible, you can use the @Input decorator in order to pass a Component reference to another Component. In that way you can call ComponentB methods from ComponentA.

For example inside FirstComponent you declare a instance variable of type SecondComponent:

 @Input()
 second: SecondComponent;

And in your Parent HTML you pass the component reference:

 <app-first [second]="second"></app-first>
 <app-second #second></app-second>

Component Interaction Cookbook

Here you have a working example: Component Interaction Example

willermo
  • 503
  • 3
  • 13
  • 1
    Wow! that really solves the problem in a simple elegant way. no need for emitting events, just passing references around. I now have direct access the other components' methods, variables, and what not.. Thanks! – Maor Barazani Sep 21 '18 at 13:36