I'm currently working on an Angular application that incorporates Bootstrap 5.2. Within this project, I have successfully implemented the Collapse component on a card, utilizing data attributes.
However, my goal is to trigger the collapse of the card's body based on a scroll event. I have fixed the card at the top of the screen, and when the user begins to scroll, I want the card's body to collapse. To achieve this, I opted to instantiate the collapse on the element using Typescript, replacing data attributes and enabling collapse toggling via Typescript click events.
Despite successfully implementing this solution, it has led to some unintended side effects. For instance, offcanvas items retain a faded background upon clicking away and dropdown elements fail to appear when clicked.
Below is how I initialized the Collapse on the card's body:
ngAfterViewInit(): void {
this.target = document.getElementById('targetID');
this.collapse = new Collapse(this.target, { toggle: false });
}
Additionally, I've incorporated logic to detect scroll changes. If the user scrolls down by 50px, it triggers the collapse to hide; otherwise, it remains visible.
ngOnChanges(changes: SimpleChanges): void {
if (changes.scrollEvent && changes.scrollEvent.currentValue !== changes.scrollEvent.previousValue) {
this.show = this.scrollEvent.target.scrollTop <= 50;
if (this.collapse) {
if (this.show) {
this.collapse.show();
} else {
this.collapse.hide();
}
}
}
}
Here is the HTML element that I am collapsing, intended to be visible by default:
<div class="collapse show" id="targetID">
<div class="card-body rounded bg-white p-1">
...content...
</div>
</div>
Am I overlooking a mistake that is causing Bootstrap elements to behave incorrectly? Alternatively, is there a method to toggle a collapse element using data attributes in response to a scroll event?