Monday, May 02, 2016

Angular 2: Injecting Parent and Child Component

Live Demo
Github Repo

To inject children component into a parent component, use ViewChildren (notice there is also ConentChildren which will inject children from content projection).

To inject a parent into child component, you simply need to inject parent in the constructor of child component. However, there is a bit of problem due to circular reference. The parent component has to reference child component as directive. If the child also depends on parent, we will get an error like this: EXCEPTION; Cannot resolve all parameters for '[ParentComponent]'.... So, the following slightly twisted injection is needed:
        contructor(@Inject(forwardRef(() => ParentComponent)) private _parent: ParentComponent)

A small working example showing both child and parent component injection can be downloaded here: https://github.com/huguogang/ng2tsdemo/blob/master/view_child.html.

No comments: