ngIf- Expression has changed after it was checked. Previous value: 'ngIf: false'. Current value: 'ngIf: true'

Issue

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.

Solution

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.

     })
  }

}

Answered By – Ashish Kadam

Answer Checked By – David Goodson (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.