Angular notes: Pass data from the child component to the parent container
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:
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 :-)