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

标签 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 [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/

相关文章:

javascript - 浏览器无法显示json数据

javascript - Angular + RequireJs : Resolve templateUrls of directives

Angular - 如何获取没有exportAs的指令的引用

Angular 响应式(Reactive)验证

Javascript html替换标签不起作用

javascript - 从视频中删除 TextTrack

javascript - 删除评论而不刷新页面

http - 使用 Ionic 2/Angular 2 保持列表更新

java - Angular 2 应用程序部署在 JBOSS 6.4 eap 上,以 java 服务作为后端

angular - 如何运行 ng 相关命令作为其显示错误