2

I have a following function inside a child component:

reload() {
    clearInterval(this.points);
    this.initiateInterval();
    this.redrawImages();
}

It's redrawing few images on window.resize event.

But in the parent component, I have a button menu-burger which shrunks the window. I want to bind to this button the reload() function from the child component.

This is my button from the parent component:

<button class="collapseMenuIcon" (click)="toggleMenu()">

I was looking for other questions about it on Stack, but in my case - this reload function uses a lot of stuff in this child component.

Also few solutions from other questions are deprecated, because Angular2 changes often.

Thank you in advance, I will upvote all answers.

2 Answers 2

3

A shared Service is a very good option. Just to throw another option out there, depending on your use case, you can just use a Subject between the parent and child without the service, if you want.

Declare Subject in child:

import { Subject } from 'rxjs/Subject';

public static fireEvent: Subject<boolean> = new Subject();

and subscribe in your constructor:

constructor(....) {
    MyChildComponent.fireEvent.subscribe(res => {
        this.reload();
    });
}

And in your parent:

import { MyChildComponent } from './my-path';

and on your button click, tell child to fire reload-method:

toggleMenu() {
  MyChildComponent.fireEvent.next(true);
}
Sign up to request clarification or add additional context in comments.

Comments

0

There are several ways to communicate between components. I personally use a service for that purpose, and it works great for me.

Read here: https://angular.io/docs/ts/latest/cookbook/component-communication.html

The last example (the service one) is the one that I use, and is quite simple to implement.

Edit:

Using services allow you to have independent components, being able to use them in other parts of the app. You also can send/receive data and the communication is both sides. I strongly recommend this method.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.