1 | initial version |
We can use the @ViewChildren decorator in Angular to get all the child components that belong to a parent component, and then use the length property to determine the total number of nth children elements.
Here is an example code snippet to demonstrate this:
In the parent component template:
<div #parent>
<app-child></app-child>
<app-child></app-child>
<app-child></app-child>
</div>
In the parent component class:
import { Component, ViewChildren, QueryList, ElementRef } from '@angular/core';
@Component({
selector: 'app-parent',
templateUrl: './parent.component.html',
styleUrls: ['./parent.component.css']
})
export class ParentComponent {
@ViewChildren('parent > app-child') childComponents: QueryList<ElementRef>;
getNumberOfChildren(): number {
return this.childComponents.length;
}
}
Explanation: