简体   繁体   English

角度:在重复对象中检测菜单项外部单击的最佳实践

[英]Angular: Best practice to detect click outside of a menu item in a repeated object

We can follow this approach Detect click outside element? 我们可以按照这种方法检测外部点击元素吗? in Angular as well with HostListner. 在Angular中也可以与HostListner一起使用。

In my component I have registered a host listener which listens on document click and hide the menu inside my component. 在我的组件中,我注册了一个主机侦听器,该侦听器侦听文档单击并隐藏组件中的菜单。 This approach works fine with a single component. 这种方法仅需一个组件即可正常工作。 However I am a bit concerned about the performance when the component is instantiated(in a list) 100 times each component registers document on click and do some processing to hide the menu opened from its component if any. 但是,我有点担心当组件实例化(在列表中)每个组件100次单击时的性能,并在单击时进行一些处理以隐藏从其组件中打开的菜单的处理。

I can move the code outside the component list but then I need to hold references of each component to detect which one has opened menu and should be closed. 我可以将代码移到组件列表之外,但是随后我需要保留每个组件的引用,以检测哪个组件已打开菜单并且应该关闭。

None of these two approach is perfect is there some other way to handle this efficiently as well as without leaking the component code in its parent? 这两种方法都不是完美的,是否还有其他方法可以有效地处理此问题以及不泄漏其父代中的组件代码?

Instead of setting the HostListener on the component, use it in a directive and set it on that component's wrapper. 与其在组件上设置HostListener,不如在指令中使用它,然后在该组件的包装器上对其进行设置。 The wrapper could be an ng-container if you wish to not have template modification. 如果您不希望修改模板,则包装器可以是ng容器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM