I have a viewChild element which I show/hide by assigning a boolean value to it.
<div #acc class="user-info" [ngClass]="{'showDropdown': accountDropdownService.userDropdownIsVisible}">
<div class="user-name">
<div class="color-1 full-name">{{userdata.FirstName}} {{userdata.LastName}}</div>
<div class="opened-eye-icon color-6__fm icon-icon_visible_off"
[class]="balanceService.showBalance ? 'icon-icon_visible_off' : 'icon-icon_visible'"
(click)="balanceService.toggleBalanceVisibility()"></div>
</div>
<div class="user-id color-6__fm">{{'General.Id'}}: <span><strong>{{userdata.Id}}</strong></span></div>
</div>
and its .ts file
@ViewChild('acc') public acc: ElementRef;
this.renderer.listen('window', 'click', (e: Event) => {
if (e.target !== this.acc.nativeElement) {
console.log('outside');
console.log(e.target);
}
});
I need to hide viewChild element when I clicking outside of it, but when I click on its child elements like user-name or user-id its also understand as an outside click.
How can I prevent this when I'm clickin on div's children elements?
You want to make sure the target is not a descendant of the container, not just the container itself. You should use contains() instead.
this.renderer.listen('window', 'click', (e: Event) => {
if (!this.acc.nativeElement.contains(e.target)) {
console.log('outside');
console.log(e.target);
}
});
Otherwise, you would want to stop the propagation in the click event handlers for the children, that way this window listener won't see the event. But that might be more work for you than necessary.