Angular2:得到子组件的数量 - 在生命周期中以及如何 [英] Angular2: get the count of child components - when in the lifecycle and how

查看:54
本文介绍了Angular2:得到子组件的数量 - 在生命周期中以及如何的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,为了便于说明,我可以说我有两个组件

So, for illustration purposes lets say I have two components


  • tabset


    • tabitem

    其中tabset是包含许多tabitems的父级

    where tabset is the parent that has many tabitems


    • tabset


      • tabitem1

      • tabitem2

      • tabitem3

      • etc ...

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

        所以,根据tabset里面有多少个tabitems,我会计算一些东西......

        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>
        

        那我该如何离开这里?
        在tabset的生命周期中,我会知道实际上有多少元素?我是否需要使用带有 ElementRef getElementsByTagName 的vanilla javascript?或者还有其他更友好的方式吗?

        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?

        一个额外的问题......如何通过 ng-content ?

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

        tabset.html

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


        推荐答案

        @ContentChildren(TabItem) tabItems:QueryList<TabItem>;
        
        ngAfterContentInit() {
          console.log(this.tabItems.toArray().length);
        }
        

        这篇关于Angular2:得到子组件的数量 - 在生命周期中以及如何的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆