'Angular: access ALL nested child components (of a subtype) while using structural directives
Okay so this question goes beyond the simplified examples in the documentation of @Viewchildren or @ContentChildren.
In our Angular project, a lot of our components are instantiated dynamically based on a type property. Suppose there is this basic element class
export abstract class Element {
public type: 'Chart' | 'Container' | ...
}
and we then layout an element
<ng-container [ngSwitch]="element.type">
<ng-container *ngSwitchCase="'Chart'">
<app-chart-switch [element]="element">
</app-chart-switch>
</ng-container>
....
<ng-container *ngSwitchCase="'Container'">
<app-container-switch [element]="element">
</app-container-switch>
</ng-container>
</ng-container>
Where elements of type 'container' have multiple children as well. E.g. a row container which lays out children horizontally. So the app-container-switch would look like this
<ng-container [ngSwitch]="element.containerType">
<ng-container *ngSwitchCase="'Row'">
<app-row [element]="element">
</app-row>
</ng-container>
</ng-container>
Which would in turn display all element's children.
<div class="row">
<ng-container *ngFor="let child of element.children" class="col">
<app-element-switch [element]="child"></app-element-switch>
</ng-container>
</div>
and we arrive again at the first switch to continue displaying children dynamically.
As not to do the entire explanation, it can be said in short that everything is generated very dynamically with an hierarchical structure and nothing is known beforehand of how things will be displayed.
But at then end I Do want all components that are actually there in my view. I.e. all pie charts, all containers, ...
But it seems that the structural directives (ngIf, ngFor, ngSwitchCase, ...) won't let me use ViewChildren nor ContentChildren. Is there nonetheless a proper way to get all instantiated components while still using switches? If yes how and if no, is there a better way to instantiate components without switch-cases while stile using the type properties of my element?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
