How to call method from one component to another when it has no parent child relation?
I have 2 sibling components and as below:
header.ts
private postValues() {
this._PartService.PostDataValues(this.search)
.subscribe(result => {
})
}
part.ts
this._PartService.getMasterData()
.subscribe(result => {
})
In this case I need to call postValues() method into getMasterData() to get some description values, and it has no parent and child communication.
It's not possible to trigger a sibling component method directly, but there is a way to trigger sibling component event using import { BehaviorSubject } from 'rxjs';
I use this approach to pass data to sibling component but it's work as well if you trigger event.
First You Create Service, Service that I call it DataService.ts
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Injectable()
export class DataService {
private triggerEventMsg = new BehaviorSubject(false);
triggerEvent = this.triggerEventMsg.asObservable();
constructor() { }
triggerEvent(val: boolean) {
this.messageSource.next(message)
}
}
Now One Component Trigger another Component, For now, Com1 trigger Com2 event.
Com1 trigger DataService triggerEvent with pass boolean value.
Com1.component.ts
import { Component, OnInit } from '@angular/core';
import { DataService } from "../data.service";
@Component({
selector: 'app-com1',
template: `
{{message}}
<button (click)="newMessage()">New Message</button>
`
})
export class Com1 implements OnInit {
constructor(private data: DataService) { }
ngOnInit() {
}
com1ClickEvent() {
this.data.triggerEvent(true);
}
}
Com2 Observe that variable when data change the method trigger in Com2 Component.
Com2.component.ts
import { Component, OnInit } from '@angular/core';
import { DataService } from "../data.service";
@Component({
selector: 'app-com2',
template: `
<p>Com2</p>
`
})
export class Com2 implements OnInit {
constructor(private data: DataService) { }
ngOnInit() {
this.data.triggerEventMsg.subscribe(message => {
// Do What ever you want.
})
}
}
My solution is to use
ngAfterViewChecked(){
this.cdRef.detectChanges();
}
in the component that you get the error
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With