Alberto Menendez
Alberto Menendez

Reputation: 535

How to listen when a ChildComponent changes and then execute a method in the ParentComponent?

I'm looking for a clean and efficient solution in Angular 7 to execute a method in a component every time a child component changes.

Given a ParentComponent rendering a ChildComponent, I need to know when the ChildComponent was changed and then execute the function in the ParentComponent.

By change I'm referring to changes in the view or in any property in the Child class.

Thanks.

Upvotes: 0

Views: 1985

Answers (2)

Kostis Tr
Kostis Tr

Reputation: 71

Prettyfly's answer seams acceptable, but there is the alternative of a service.

I find this link quite descriptive.

Create an observable(ex. RXJS's subject) in the service and subscribe to it at your parent component, so as to keep track of its changes and handle them accordingly.

At the dynamically created component, in onChanges lifecycle hook or in any action based function, you can trigger the observable to emit changes (which then the parent/any other subscriber will 'listen' through the subscription)

Just remember to provide the service in the parent component, so as the parent and its children share the same service instance, or in app.module to make it global for the whole app.

Services also enable biderictional data sharing among parent, child and sibling components.

EDIT: In case you don't use <ng-template> and component is created on the fly, you can manually detect its changes by passing its reference to 'componentRef' and calling componentRef.changeDetectorRef.detectChanges();

Upvotes: 3

prettyfly
prettyfly

Reputation: 3130

Create an EventEmitter in the child component, and emit when it changes.

Subscribe to the event-emitter from the parent component's template, and execute your function each time it emits.

e.g

parent.component.html

<child-component (changeEmitter)="executeParentFunction()"> </child-component>

child.component.ts

@Output() changeEmitter: EventEmitter<boolean> = new EventEmitter<boolean>();

ngOnChanges() {
    this.changeEmitter.emit(true);
}

The ChildComponent is provided dynamically and having an @Input to be called is not an option. It's has to be transparent for the child component.

This will still apply. As long as the child component is the one in control of emitting on change, then any parent can subscribe to it, even when dynamically added.

Upvotes: 2

Related Questions