#Angular2 如何计算自定义属性指令的数量?



我做了一个自定义attr directive,我将在兄弟姐妹元素中使用它,例如:

<div>
<div [customAttrDirective]="'value'">1</div>
<div [customAttrDirective]="'value'">2</div>
<div [customAttrDirective]="'value'">3</div>
<div [customAttrDirective]="'value'">4</div>
</div>   

我做了一个控制我所有指令的service。在其中,我想知道我的指令计数customAttrDirective.

PS:我不能通过按类名搜索来做到这一点(因为我在指令中添加了类(,也不能通过按属性(指令名称(搜索来做到这一点,因为角度会发生变化。

编辑:将错误的 sintaxcustomAttrDirective="'value'"替换为[customAttrDirective]="'value'"

非常感谢。

假设自定义属性指令的类名是CustomAttrDirective,在使用自定义指令的组件中,添加以下内容:

@ViewChildren(CustomAttrDirective) dirs: QueryList<CustomAttrDirective>

然后在生命圈ngAfterViewInit,得到变dirs的长度。

最新更新