最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin3浏览0评论

So, for illustration purposes lets say I have two ponents

  • 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 ponent)...

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 ponent's reference via ng-content?

tabset.html

<div class="...." #tabset>
    <ng-content></ng-content>

So, for illustration purposes lets say I have two ponents

  • 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 ponent)...

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 ponent's reference via ng-content?

tabset.html

<div class="...." #tabset>
    <ng-content></ng-content>
Share Improve this question edited Oct 13, 2016 at 14:05 Demiro-FE-Architect asked Oct 13, 2016 at 13:56 Demiro-FE-ArchitectDemiro-FE-Architect 3,74014 gold badges55 silver badges87 bronze badges 1
  • 1 You could use @ContentChildren(TabItem) items: QueryList<TabItem>; – Paul Samsotha Commented Oct 13, 2016 at 14:06
Add a ment  | 

1 Answer 1

Reset to default 9
@ContentChildren(TabItem) tabItems: QueryList<TabItem>;

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

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

发布评论

评论列表(0)

  1. 暂无评论