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

Javascript #Angular2如何计算自定义属性指令的数量?,javascript,angular,angular-directive,angular-services,custom-directive,Javascript,Angular,Angular Directive,Angular Services,Custom Directive,我制作了一个自定义的attr指令,我将在兄弟元素中使用它,如: <div> <div [customAttrDirective]="'value'">1</div> <div [customAttrDirective]="'value'">2</div> <div [customAttrDirective]="'value'">3</div> <div [customAttrDire

我制作了一个自定义的
attr指令
,我将在兄弟元素中使用它,如:

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

1.
2.
3.
4.
我也做了一个
服务
,控制我所有的指令。在这里面,我想知道我的指令的计数
customAttrDirective

PS:我不能按类名搜索(因为我在指令中添加了类),也不能按属性搜索(指令名),因为角度变化

编辑:将错误的sintax
customAttrDirective=“'value'”
替换为
[customAttrDirective]=“'value'”


非常感谢

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

@ViewChildren(CustomAttrDirective)dirs:QueryList


然后在生命周期
ngAfterViewInit
中,获取变量
dirs

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

@ViewChildren(CustomAttrDirective)dirs:QueryList


然后在生命周期
ngAfterViewInit
中,获取变量
dirs

的长度,我猜你没有按照你给出的示例中的方式使用,否则你会将它们放在一个ngs中,这样就可以进行计数,对吗?你是对的。我有一个语法错误,编辑它,对不起,我猜你没有按照你给出的例子的方式使用,否则你会把它们放在一个NGF中,这样就可以计算了,对吗?你是对的。我有一个语法错误,编辑它,所以你得到你的计数了吗?没有,我需要用服务来做。将你的服务注入到组件中,并将计数保存到你的服务中,然后你可以在其他组件中访问计数。我使用了这个
this。dirs
ngAfterViewInit
中未定义,我使用的组件是我的指令的父组件。你得到你的计数了吗?没有,我需要使用服务。将你的服务注入组件并将计数保存到你的服务中,然后你可以访问其他组件中的计数。我使用了这个
这个。dirs
ngAfterViewInit
中未定义,我使用的组件是我指令的父组件。