Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

212
Views
How to pass data between sibling components in Angular, by 'sending the message/calling the function' from ngOnInit()?

I want to send message from ComponentA to ComponentB. And I am using service for that. Here is the code- My problem is if I call sendInfoToB() from componentA's html file (event hooked to a button click), then I'm recieving the message in componentB /getting console.log(this.check); and console.log(message); 's values in the console.. but when I call this.sendInfoToB(true); from componentA's ngOnInit() then I get no message in console for componentB. I want the message when I call from componentA's ngOnInit. How can I achieve that? Please help. Thank you in advance.

ComponentA.ts

constructor(private siblingService: SiblingService,) {}

public dataX: boolean = false;
someFunc(){
//some calculation returning true
  this.dataX = true;
}

ngOnInit() {
    this.someFunc();
    this.sendInfoToB();
}

sendInfoToB() {
    this.siblingService.communicateMessage(dataX);
}

message.service.ts

export class SiblingService {
    sendMessage = new Subject();
    constructor() {}

    communicateMessage(msg) {
        this.sendMessage.next(msg);

    }
}

ComponentB.ts

constructor(private sibService: SiblingService,) {}

ngOnInit() {
        
        this.sibService.sendMessage.subscribe((message) => {
            this.check = message;
            console.log(this.check);
            console.log(message);
        });
    }
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

More than likely this has to do with order of operations. Component A is created and sends the message, then Component B gets created and subscribes to new messages. Since you are using a Subject it only gives you messages sent after you subscribe to it.

The easiest strategy to this is to use a BehaviorSubject.

export class SiblingService {
    sendMessage = new BehaviorSubject();
    constructor() {}

    communicateMessage(msg) {
        this.sendMessage.next(msg);

    }
}

The other way is to send the message after the init happens, like on a click event.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!