Search code examples
angularviewchild

angular 2 re-render parent component from @ViewChild Component


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();

Solution

  • 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) {}