I’m working on an Angular application where I have a filter component that toggles its visibility based on a click outside event. This works as expected, but I have an issue when there is a calendar component inside the filter area. Interacting with the calendar (e.g., selecting dates) triggers the click outside event, causing the filter component to close.
Here’s my filter component code:
...
showFilter = false;
private globalClickListener: () => void;
// List of classes to ignore during the click outside check
ignoredClasses = [
'.mat-select',
'.mat-datepicker',
'span.mat-option-text',
'span.mat-calendar-body-cell-content.mat-focus-indicator.mat-calendar-body-selected',
'button.mat-calendar-previous-button.mdc-icon-button.mat-mdc-icon-button.mat-unthemed.mat-mdc-button-base.cdk-focused.cdk-mouse-focused',
'button.mat-calendar-next-button.mdc-icon-button.mat-mdc-icon-button.mat-unthemed.mat-mdc-button-base.cdk-focused.cdk-mouse-focused',
'.mat-calendar-body-cell-content.mat-calendar-body-selected'
];
constructor(
...
filterService
.openCloseFilterEvent()
.subscribe(() => (this.showFilter = !this.showFilter));
filterService.dataFilterEvent().subscribe(() => (this.showFilter = false));
}
ngOnInit() {
this.globalClickListener = this.renderer.listen('document', 'click', (event: Event) => {
const clickedElement = event.target as HTMLElement;
const isIgnoredElement = this.ignoredClasses.some(selector => clickedElement.closest(selector));
if (!this.el.nativeElement.contains(event.target) && !isIgnoredElement) {
this.showFilter = false;
}
});
}
ngOnDestroy() {
if (this.globalClickListener) {
this.globalClickListener();
}
}
searchEmitter(event: Event) {
event.stopPropagation();
this.filterService.setPage(25, 0);
this.filterService.updateFilter(this.filter);
this.showFilter = false;
}
}
The ignoredClasses/isIgnoredElement was just one of my attempts, it didn’t work and I am not sure why, perhaps because the calendar is not a direct parent or child? it is part of another pieces of components, they are not in the same .html file? I tried it because it works on another project I have.
Anyhow, anyone knows how I can make it work? or what else I could attempt?
I tried the ignoredClasses as an array and outside the array, I am not sure what else I can try