How can I add an eventlistener
on a <div>
or other element, to hide something I am displaying via an *ngIf
- using Angular, when I click away from that element?
Explanation: I am showing a custom CSS dropdown via *ngIf
when you click on <label>Filter</label>
, and I want the user to be able to click as many times as they wish in the custom dropdown, but when they click outside the custom dropdown, I would like to hide the custom dropdown via the *ngIf
again.
The method called when a user clicks on the label is showHideSectionOptions()
, which toggles the showHide
variable to true
or false
.
This is my HTML code:
showHide = false;
<div class="form-row">
<div class="form-group" id="showAndHideSections">
<label (click)="showHideSectionOptions()">
<img src="../../../assets/icons/Filter.png" alt="" class="mr-3">Filter</label>
<div *ngIf="showHide" class="section-options">
// show or hide content
</div>
</div>
</div>
This is my component code:
showHideSectionOptions() {
this.showHide = !this.showHide;
}
I have tried adding an eventlistener as per the below, but I cannot set the value of my showHide
variable, as I get the following error: Property 'showHide' does not exist on type 'HTMLElement'.ts(2339):
body.addEventListener('click', function() {
alert('wrapper');
}, false);
except.addEventListener('click', function(ev) {
alert('except');
ev.stopPropagation();
}, false);
Thanks in advance!