Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2: get the count of child components - when in the lifecycle and how

So, for illustration purposes lets say I have two components

  • tabset
    • tabitem

where tabset is the parent that has many tabitems

  • tabset
    • tabitem1
    • tabitem2
    • tabitem3
    • etc...

So, depending on how many tabitems there are inside tabset I will calculate some stuff...

so, how do I get the item count?

(the item count should be accessible in the child component)...

so I have reference of the parent like this

<tabset #tabset>
    <tabitem [tabset]="tabset">....</tabitem>
    <tabitem [tabset]="tabset">....</tabitem>
    <tabitem [tabset]="tabset">....</tabitem>
</tabset>

So how do I go from here? When in the life-cycle of tabset I will know how many elements there are actually in? and do I need to use vanilla javascript with ElementRef and getElementsByTagName ? Or is there any other, more angular friendly way?

One extra question.... how can I pass the component's reference via ng-content?

tabset.html

<div class="...." #tabset>
    <ng-content></ng-content>
like image 337
DS_web_developer Avatar asked Oct 13 '16 13:10

DS_web_developer


People also ask

How to emit data from child to parent in Angular?

Otherwise, remember the three steps: Prepare Child component to emit data. Bind Property in Parent Component template. Use Property in Parent Component class.

What is the use of@ ViewChild in Angular?

The @ViewChild decorator allows us to inject into a component class references to elements used inside its template, that's what we should use it for. Using @ViewChild we can easily inject components, directives or plain DOM elements.

What is parent component and child component in Angular?

concept parent component in category angularA parent component can pass data to its child by binding the values to the child's component property. A child component has no knowledge of where the data came from. A child component can pass data to its parent (without knowing who the parent is) by emitting events.


1 Answers

@ContentChildren(TabItem) tabItems: QueryList<TabItem>;

ngAfterContentInit() {
  console.log(this.tabItems.length);
}

Note: TabItem can be a component too, not only a directive

like image 123
Günter Zöchbauer Avatar answered Sep 29 '22 08:09

Günter Zöchbauer