call a function in a component from another component

陌路散爱 提交于 2019-11-28 14:06:56
Seid Mehmedovic

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

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!