Call a function in a component from another component

In Angular2, let's say I have component1 (use it as nav on the left) 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 cannot use event binding here.

+2


source to share


2 answers


A shared service is a generic way of communication between unrelated components. Your components must use a single instance of the service , so make sure it's listed at the root level.

General 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 also be helpful: Angular 2 Interoperability between components using a service

+2


source


You can use angular BehaviorSubject to communicate with unrelated 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 the above approach, you can easily reference unrelated components with method / share.

More information here

0


source







All Articles