I am currently developing an Angular application that includes a filter component with visibility toggled based on a click outside event. While this functionality works correctly, I encountered an issue when incorporating a calendar component within the filter area. Interacting with the calendar (e.g., selecting dates) triggers the click outside event, causing the filter component to close prematurely.
Below is the code snippet for my filter component:
...
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;
}
}
Despite attempting to use ignoredClasses/isIgnoredElement as a solution, it did not yield the expected results. This may be due to the fact that the calendar component is not directly related in hierarchy to the filter component. The calendar and other components are located in separate files, unlike in my previous project where a similar approach worked seamlessly.
If anyone has insights on how to address this issue or suggest alternative solutions, I would greatly appreciate your input. I have tried utilizing the ignoredClasses both as an array and individually, but I am open to exploring other possibilities.