Angular 2中实现点击文档及选中选项时移除下拉框active类
To fix this, you have two robust approaches to remove the 'active' class when a user selects an option from your dropdown. Here's how to implement both:
Approach 1: Use the change Event (Recommended)
The change event fires whenever the dropdown's selected value changes—this includes both mouse clicks on options and keyboard navigation (like using arrow keys to select an option). This is the most inclusive solution:
ngAfterViewInit() { const elem = this.element.nativeElement.querySelector('select'); const option_elem = this.element.nativeElement.querySelectorAll('option'); // Existing document click listener this.renderer.listen(document.body, 'click', (event) => { if (event.target == elem) { this.addClass(elem, 'active'); } else { this.removeClass(elem, 'active'); } }); // New change listener for the select element this.renderer.listen(elem, 'change', () => { this.removeClass(elem, 'active'); }); }
Approach 2: Listen to Clicks on Individual Options
If you specifically want to target only mouse clicks on options (not keyboard selection), you can add click listeners to each option element:
ngAfterViewInit() { const elem = this.element.nativeElement.querySelector('select'); const option_elem = this.element.nativeElement.querySelectorAll('option'); // Existing document click listener this.renderer.listen(document.body, 'click', (event) => { if (event.target == elem) { this.addClass(elem, 'active'); } else { this.removeClass(elem, 'active'); } }); // Add click listeners to each option option_elem.forEach(option => { this.renderer.listen(option, 'click', () => { this.removeClass(elem, 'active'); }); }); }
Why This Works:
- Approach 1: The
changeevent triggers immediately when the user selects a new option, regardless of how they interact with the dropdown. This ensures the 'active' class is removed no matter the input method. - Approach 2: Each option gets a click handler that directly removes the 'active' class from the parent select element when clicked.
Either of these will complement your existing document click listener to fully handle removing the 'active' class whenever the user interacts with the dropdown options.
内容的提问来源于stack exchange,提问作者Anupama_K

