Ask Your Question

Revision history [back]

click to hide/show revision 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:

  • We use the #parent template reference variable to reference the parent div element in the template.
  • We use the @ViewChildren decorator to get all the app-child components that belong to the parent div element.
  • The @ViewChildren decorator returns a QueryList object containing all the matching components.
  • We use the length property of the QueryList object to get the number of nth children elements.
  • We define the getNumberOfChildren() method to return the length of the childComponents QueryList. This method can then be called from the parent component template to display the total number of nth children elements.