Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

call a function in a component from another component

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.

like image 755
Sara N Avatar asked Jan 05 '23 11:01

Sara N


2 Answers

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

like image 59
Prashobh Avatar answered Jan 07 '23 01:01

Prashobh


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

like image 23
seidme Avatar answered Jan 07 '23 01:01

seidme