3

I am working on angular2 application where I have parent component that pops up a child component

@ViewChild(childPopupComponent) case: childPopupComponent;

What I want to do is: when pressing save button from the child component (which is popup inside the parent component), re-render the parent one for reflection to take place (instead of reloading the whole page).

I know that this re-render the current component, but how to do that from the @ViewChild one

this.ref.detectChanges();

1 Answer 1

2

Inject ChangeDetectorRef in your child component like:

export class childPopupComponent {
    constructor(public cdRef: ChangeDetectorRef) {}

and after that you will be able to run change detection cycly only on child component:

@ViewChild(childPopupComponent) case: childPopupComponent;

this.case.cdRef.detectChanges();

For updating parent you can inject it in child

export class childPopupComponent {
    constructor(public parent: ParentComponent) {}

and then

this.parent.cdRef.detectChanges()

or even try this:

import { ChangeDetectorRef, SkipSelf } from '@angular/core';

export class childPopupComponent {
    constructor(@SkipSelf() private parentCdRef: ChangeDetectorRef) {}
Sign up to request clarification or add additional context in comments.

4 Comments

Really thank you, and If I wanted to inject the whole parent component inside the child in order to call a parent function from the child.. how can I do that as It throws strange error Can't resolve all parameters for casesPopupComponent: ([object Object], [object Object], [object Object], [object Object], [object Object], [object Object], ?)
? usually happens with circular dependency. You can provide abstract class to solve it stackoverflow.com/questions/43198098/…
Another solution for you is having @Ouput events on your child component and within parent template just subscrive to it <child (somethingChanged)="onHandleWithParentMethod()" This way you do not need to solve problem with circular dependency
Thank you yurzui, very useful

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.