less than 1 minute read

Well there are many ways of parent child communication and interaction in angular, e.g. @Input binding, setter, ngOnChanges(), EventEmitter, via local variable, @ViewChild(), via a service, and so on…

ViewRefContainer

We will look at communication via ViewContainerRef . ViewContainerRef represents a container where one or more views can be attached to a component.

The concept is pretty straightforward, get the reference of the (parent) view container and modify the values, or call a method. Now lets look at the code:

Lets say we have a variable Name in the ParentComponent and we want to modify it from ChildComponent using the method SayMyName().

export class ChildComponent {
  constructor(private viewContainerRef: ViewContainerRef) { }
  getParentComponent(): ParentComponent{
        return this.viewContainerRef[ '_data' ].componentView.component.viewContainerRef[ '_view' ].component
    }
  SayMyName() {
    this.getParentComponent().Name = 'My name is Slim Shady!';
  }
}

Its as simple as that!

You can also view this example on Stackblitz.

Support me with ETH: 0x681a83007bC52C0bF42B41263Dc498f9Ef7af02A

Leave a comment