call a function in a component from another component

23,775

Solution 1

You can use angular BehaviorSubject for communicating with non related component.

Service file

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';


@Injectable()
export class commonService {
    private data = new BehaviorSubject('');
    currentData = this.data.asObservable()

    constructor() { }

    updateMessage(item: any) {
        this.data.next(item);
    }

}

First Component

constructor(private _data: commonService) { }
shareData() {
      this._data.updateMessage('pass this data');
 }

Second component

constructor(private _data: commonService) { }
ngOnInit() {
     this._data.currentData.subscribe(currentData => this.invokeMyMethode())
}

Using above approach you can invoke a method/share data easily with non related components.

More info here

Solution 2

Shared service is a common way of communication between non-related components. Your components need to use a single instance of the service, so make sure it's provided at the root level.

Shared service:

@Injectable()
export class SharedService {

    componentOneFn: Function;

    constructor() { }
}

Component one:

export class ComponentOne {

    name: string = 'Component one';

    constructor(private sharedService: SharedService) {
        this.sharedService.componentOneFn = this.sayHello;
    }

    sayHello(callerName: string): void {
        console.log(`Hello from ${this.name}. ${callerName} just called me!`);
    }
}

Component two:

export class ComponentTwo {

    name: string = 'Component two';

    constructor(private sharedService: SharedService) {
        if(this.sharedService.componentOneFn) {
            this.sharedService.componentOneFn(this.name); 
            // => Hello from Component one. Component two just called me!
        }
    }
}

This post might be helpful as well: Angular 2 Interaction between components using a service

Share:
23,775
Sara N
Author by

Sara N

web/windows Developer

Updated on February 13, 2020

Comments

  • Sara N
    Sara N about 4 years

    In Angular2 , assume I have component1(use it as left panel navigator) and component2 .these two components are not related to each other (sibling, parent and child, ...). how can I call a function in component1 from component2? I cant use event binding here.