3
votes

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?

2
angularfirebase.com/lessons/… if you scroll down there is an example of sharing data with a service.Jason White

2 Answers

8
votes

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);
    });
  }
1
votes

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