How to Take Out the Active Class from a Dropdown Menu in Angular 2

I am having trouble removing the 'active' class from a dropdown when an option is selected. I have successfully removed it on document click, but need help with removing it on selection.

TS :

ngAfterViewInit() {
        const elem = this.element.nativeElement.querySelector('select');
        const option_elem = this.element.nativeElement.querySelectorAll('option');
        this.renderer.listen(document.body, 'click', (event) => {
            if (event.target == elem) {
                this.addClass(elem, 'active');
            }
            else {
                this.removeClass(elem, 'active');
            }
        });

        for(var i=0; i<=option_elem.length; i++){
             this.renderer.listen(option_elem, 'click', (event) => {
                 this.removeClass(elem,'active');
             });
         }
    }

HTML :

<div class="dropdown">                
    <select class="dropdown-menu" aria-labelledby="dropdownMenuButton" name="menu" id="menu">
         <option class="dropdown-item" *ngFor="let item of selectOption" [value]="item.value"> {{item.label}}</option>
    </select>
</div>

Any assistance would be greatly appreciated. Thank you!

Answer №1

Avoid manually adding and removing classes. Utilize Angular data bindings to handle this task for you. Incorporate [class.active] binding alongside [(ngModel)] on the select element.

component.html

<div class="dropdown">                
  <select class="dropdown-menu" aria-labelledby="dropdownMenuButton" name="menu" id="menu" [(ngModel)]="selected" [class.active]="selected === null">
    <option class="dropdown-item" *ngFor="let item of selectOption" [value]="item.value"> {{item.label}}</option>
  </select>
</div>

component.ts

selected = null;

Answer №2

Modify option_element to option_element[i], since option_element is now an array.

for(var i=0; i<=option_elem.length; i++){
  this.renderer.listen(option_elem[i], 'click', (event) => {
     this.removeClass(elem,'active');
  });
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The functionality of CSS isn't up to snuff on Mozilla Firefox

I am having an issue with CSS styling on a <div> element in my PHP page. The CSS style is working perfectly in Google Chrome, but when I test my code in Firefox, the styling is not being applied. .due-money { background-color: #09C; color: whi ...

My webpage layout doesn't quite accommodate my content, so I need to adjust it to be more zoom

Why does the page container load bigger than the html/body container in mobile mode, as shown in the photo? https://i.sstatic.net/fD1N4.png Here is my CSS: html { margin-top: 48px; width: 100%; } body { margin: 0; width: 100%; background: ...

Generate Angular 9 HTML-formatted output with a return function statement

I am currently working on displaying a table using ngFor. I have encountered an issue with one particular column where a string needs to be displayed as two separate lines. I attempted to split the string into two array values using a function, but when re ...

Transforming navigation bar dropdown appearance using solely HTML5, CSS, and jQuery

Currently experimenting with a navigation bar where each component is skewed at -30 degrees. Upon clicking any piece, its corresponding content drops down for display below the clicked item. I am aiming to have the section of the clicked piece expand into ...

Using $_POST method to navigate within the same web page

<!doctype html> <html> <head> <meta charset="UTF-8"> <title>PHP links</title> <?php echo '<div style="background-color:#ccc; padding:20px">' . $_POST['message'] . '</div>'; ...

What is the best way to include a maximum height in my ScrollToBottom element?

I am currently attempting to limit the maximum height of my component as adding user messages causes it to expand and stretch the whole page. However, I have been unsuccessful in setting a maxHeight property for the component. I am utilizing ScrollToBottom ...

What is the best way to align paragraphs vertically within a required square-shaped div using CSS (with images for reference)?

I am trying to style a table in a specific way, but I'm facing some challenges. First, I want to make the internal div inside the table square with a percentage height. Next, I need to have two paragraphs stacked on top of each other within the same ...

Angular 4: Converting JSON Data into CSV Format

Can anyone assist me in converting a JSON file to CSV in Angular 4? Is there an existing external plugin that can help with this task? I came across a plugin called json2csv. However, I'm unsure of how to integrate it into my Angular 4 project. ...

Creating a unique slider using CSS animations and JavaScript

After hours of research, I have hit a roadblock with my custom slider project. I am reaching out to fellow developers for help and hoping that my experience can benefit others facing a similar challenge. The goal is to create a custom slider with animated ...

The NgRx Store encountered an error: Unable to freeze

I am currently developing a basic login application using Angular, NgRx Store, and Firebase. I have implemented a login action that is supposed to log in to Firebase and store the credentials in the store. However, it seems like there is an issue in my imp ...

What is the process for integrating a tensorflow.js model into a React-based web application?

I've been working on a React web application in Typescript that involves loading a tensorflow.js model and then applying it each time the component updates. While I successfully implemented this in a small demo app without React, I am facing some chal ...

How to align text to the left in Bootstrap 4 with equal column widths reminiscent of a

Below is a snippet of code that creates a list of links: <h3>Hours</h3> <div class="hours-display pb-2"> <div class="mb-0"><span class="mr-2"><strong>Mon</strong></span><span class="mr-1">9:30</sp ...

What is the best way to implement this object builder in TypeScript strict mode without adding unnecessary weight to it?

After coming across a builder pattern online that I really liked, I found that it doesn't work in strict mode due to receiving the same error for the first 3 properties: (property) PizzaBuilder.numberOfSlices: number Property 'numberOfSlices&apo ...

Troubleshooting Jasmine Unit Testing issues with the ng-select library

Recently, I integrated the ng-select component from Github into my Angular application without encountering any console errors during runtime. It functions as expected; however, issues arise when running unit tests with Jasmine. To incorporate NgSelectMod ...

The jQuery plugin for mmenu does not activate the selected menu item

I recently implemented a jQuery menu plugin that I found on Overall, everything is functioning correctly. However, I am encountering an issue where the active state is not displayed when selecting a sub menu. Instead, it keeps redirecting to the main page ...

Is there a way to modify the FixedTableHeader jQuery plugin to include a fixed first column in addition to the fixed header?

I've been experimenting with a jQuery plugin I found at to create a stylish table with fixed headers, sorting options, and other interesting features. While the plugin is great, I also considered using jqGrid for its impressive capabilities. However, ...

Enhanced Type Definitions for Decorated Classes in TypeScript

Check out this TypeScript Docs example showcasing decorators: function extendingClassDecorator<T extends {new(...args:any[]):{}}>(constructor:T) { return class extends constructor { newProperty = "new property"; hello = "override ...

Issue encountered during frida-il2cpp-bridge module installation

Having trouble with installing the frida module (frida-il2cpp-bridge)? I followed the steps, but encountered errors. You can check out the installation steps here. The specific error message I received is: Spawned `com.games`. Resuming main thread! Refe ...

Tips for populating class attributes from an Angular model

Suppose there is a Class Vehicle with the following properties: public id: number; public modelId: number; public modelName: string; Now consider we have an object that looks like this {id: 1, modelId: 1, modelName: "4"} What is the best way to assign e ...

Showing Bootstrap Style with Angular's NgFor and NgStyle

I'm currently working on displaying a header nav menu using a typescript object array with Bootstrap. The problem I'm facing is that the menu displays vertically instead of horizontally when using the array. I suspect it has something to do with ...