[英]Implementing a @hostListener only when component is called
Angular application that uses a ngx-datatable .使用ngx-datatable 的Angular 应用程序。 This table auto populates its
[rows]
.该表自动填充其
[rows]
。 Within these rows is an [action]
that displays a popup of items.在这些行中有一个
[action]
显示项目的弹出窗口。 This popup is a seperate component away from the table.此弹出窗口是远离表格的单独组件。 I am calling the popup from the table in a parent > child link eg
我正在从父> 子链接中的表格中调用弹出窗口,例如
<ngx-datatable-column name="Actions">
<ng-template let-row="row" ngx-datatable-cell-template>
<app-actions-pop-up [actions]="row.actions"></app-actions-pop-up>
</ng-template>
</ngx-datatable-column>
This calls the action popup component.这将调用操作弹出组件。 I have an
@HostListener
that listens to the clicks on the page for an Event
.我有一个
@HostListener
来监听页面上的点击Event
。 This then returns true/false to open or close the popup.然后返回真/假以打开或关闭弹出窗口。
This is costly as my application will have 1000's of rows and it will impact the rendering as a click is being listened too regardless of whether the actions button is being clicked on.这是昂贵的,因为我的应用程序将有 1000 行,并且它会影响渲染,因为无论是否单击操作按钮,都会监听单击。
eg if there are 4 row items, it will loop through 4 times.例如,如果有 4 个行项目,它将循环 4 次。 Imagine if there were 1000s of rows.
想象一下,如果有 1000 行。
There is a lovely solution found here: Detect click outside Angular component where by it adds a @Hostlistener()
to the document click event only once inside the popup component.这里有一个可爱的解决方案: 检测 Angular 组件外的单击,通过它在弹出组件内仅向文档单击事件添加一次
@Hostlistener()
一次。 The event should push the value of the clicked target element inside a public subject stored in a global utility service.该事件应该将单击的目标元素的值推送到存储在全局实用程序服务中的公共主题中。
However, I have struggled to implement this thus far in my setup.但是,到目前为止,我一直在努力在我的设置中实现这一点。 Any help would be appreciated here - stackBlitz example
任何帮助将不胜感激 - stackBlitz 示例
I would suggest simply adding (document:click)="clickout($event)"
on your popup container.我建议在您的弹出容器上简单地添加
(document:click)="clickout($event)"
。
html html
<div *ngIf="isActive" (document:click)="clickout($event)" class="actions__container">
ts ts
clickout(event) {
this.isActive = this.eRef.nativeElement.contains(event.target);
}
Angular will subscribe to that event only in case if popup is open and unsubscribe when it's closed.只有在弹出窗口打开并在关闭时取消订阅的情况下,Angular 才会订阅该事件。 So you will have zero or only one subscription.
因此,您将拥有零个或只有一个订阅。
You can also read one of my article regarding this optimization您还可以阅读我关于此优化的一篇文章
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.