我制作了一个自定义 attr 指令
,我将在兄弟元素中使用它,例如:
<div>
<div [customAttrDirective]="'value'">1</div>
<div [customAttrDirective]="'value'">2</div>
<div [customAttrDirective]="'value'">3</div>
<div [customAttrDirective]="'value'">4</div>
</div>
我还创建了一个服务
来控制我的所有指令。在其中我想知道我的指令 customAttrDirective
的数量。
PS:我无法通过按类名称搜索来做到这一点(因为我在指令内添加类),并且由于 Angular 变化而无法通过按属性(指令名称)搜索来做到这一点。
编辑:将错误的语法 customAttrDirective="'value'"
替换为 [customAttrDirective]="'value'"
非常感谢。
最佳答案
假设您的自定义属性指令的类名称是 CustomAttrDirective
,在您使用自定义指令的组件中,添加以下内容:
@ViewChildren(CustomAttrDirective) dirs: QueryList<CustomAttrDirective>
然后在生活圈ngAfterViewInit
,获取变量dirs
的长度.
关于javascript - #Angular2 我如何计算自定义属性指令的数量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45233430/