Angular notes: Pass data from the child component to the parent container

Olena Liebiedieva
2 min readDec 29, 2019

--

Lviv High Castle

The task is: to handle different child components in the one container with using their data on the parent level.

As example: there are several components with different forms, and all them have the same dynamic information about forms processing and validation: e.g. loading, server side errors, form title, image. And it is necessary to show this common information on the container level. Maybe for dynamic survey with different question types:

Survey container

So it needs implement container component that declare type of child components and can use their data.

import {Component} from "@angular/core";@Component({
selector: "basic-survey-layout",
templateUrl: "./basic-survey-layout.component.html",
styleUrls: ["./basic-survey-layout.component.scss"]
})
export class BasicSurveyLayoutComponent<SomeComponent> childComponent: SomeComponent; constructor() {} onRouterOutletActivate(event: SomeComponent) {
this.childComponent = event;
}
onRouterOutletDeactivate() {
this.childComponent = null;
}
}

In template:

<ng-container *ngIf="childComponent.title"></ng-container>
<ng-container *ngIf="childComponent.loading$"></ng-container>
<ng-container *ngIf="childComponent.errors$"></ng-container>
<ng-container *ngIf="childComponent.imageUrl"></ng-container>
<router-outlet
(activate)="onRouterOutletActivate($event)"
(deactivate)="onRouterOutletDeactivate()"
></router-outlet>

So all magic will done by Router. When SPA receive question type — it will show specific component in the container. And the container will know everything about child via childComponent reference.

Lets keep it simple with Angular :-)

--

--