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();
Vega
  • 27,856
  • 27
  • 95
  • 103
sockeros
  • 33
  • 3

1 Answers1

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) {}
yurzui
  • 205,937
  • 32
  • 433
  • 399
  • 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], ?) – sockeros Sep 25 '17 at 10:57
  • `?` usually happens with circular dependency. You can provide abstract class to solve it https://stackoverflow.com/questions/43198098/angular2-dependency-injection-not-working-when-injected-into-a-dynamic-compone/43198716#43198716 – yurzui Sep 25 '17 at 11:00
  • Another solution for you is having @Ouput events on your child component and within parent template just subscrive to it ` – yurzui Sep 25 '17 at 11:01
  • Thank you yurzui, very useful – sockeros Sep 25 '17 at 11:09