I know there are countless of questions around this, and I tried every solution but nothing suited my needs. Tried directives, tried it straight in my component but it didn't work a single time.
So my situation is like this; I have a tableview and at the end of every tableview you can open a small dropdown by clicking on an icon. The dropdown that pops up is a small component. So in my parent component it looks like this;
<tbody>
<tr *ngFor="let rows of subscriptionTable.data; let i = index;">
<td *ngFor="let cell of subscriptionTable.data[i].data">
<!-- Table actions -->
<div *ngIf="cell.actions && cell.actions.length > 0">
<app-dropdown
[actions] = cell.actions
(onActionClicked) = "handleSubscriptionAction($event, i)"
>
</app-dropdown>
</div>
</td>
</tr>
</tbody>
So I'm rendering multiple child app-dropdown components that look like this;
<div class="fs-action">
<div class="fs-action__dots" (click)="openActionSheet($event)">
<span class="fs-action__dot"></span>
<span class="fs-action__dot"></span>
<span class="fs-action__dot"></span>
</div>
<ul class="fs-action__list">
<li
class="fs-action__item"
*ngFor="let action of actions; let i = index;"
(click)="actionClicked( $event, i )"
[ngClass]="{'fs-action__item--danger': action.type === 'destructive' }"
>
{{ action.label }}
</li>
</ul>
</div>
What I want to do now is, that as soon as I click outside the fs-action element, the dropdown dismisses. I would like to do that inside the app-dropdown
component, then everything related to this component is in the same place.
But as soon as I attach a directive or anything else, the hostlistener
get's added for every row. Every outside click is then being triggered multiple times. Checking if I was clicking outside the action element then becomes a burden, because it then renders false for all the other hostlisteners
and true for the one that's active.
The issue is illustrated inside this stackblitz; https://stackblitz.com/edit/angular-xjdmg4
I commented the section which causes issues inside dropdown.component.ts
;
public onClickOutside( event ) {
// It executes 3 times, for each of the items that is added
// Even when clicking inside the dropdown, it calls this function
console.log("click")
}