Call a function in a component from another component
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 to share
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.
0
source to share