Click to alter the style of an <li> element

I'm currently using Angular CLI and I have a menu list that I want to customize. Specifically, I want to change the background color of the <li> element when it is clicked. I am passing an id to the changeColor() function, but unfortunately, I am encountering an issue where menuButton is returned as null. Can someone please assist me with this problem?

.html

<ul>
   <li id="menu_btn" (click)="changeColor()" >

   </li>
   <li id="menu_btn" (click)="changeColor()"> 

   </li>
<ul>

.ts:

changeColor() {
    let menuButton = document.getElementById("menu_btn"); 
    menuButton.style.backgroundColor = '#816587';
  }

Answer №1

If you want to achieve a more angular approach, you can define your menu list in an array like this:

// script.js
menuList = [
    {
        name: 'Option 1',
        isSelected: false
    },
    {
        name: 'Option 2',
        isSelected: false
    }
];

Next, utilize ngFor to display the list and utilize ngClass along with the isSelected flag of each menu item to toggle a selected class.

// index.html
<ul>
    <li *ngFor="let menuItem of menuList" (click)="changeColor(menuItem)"
        [ngClass]="{'selected': menuItem.isSelected}">
        {{menuItem.name}}
    </li>
</ul>

// style.css
.selected{
    background-color: #816587;
}

Ensure that your changeColor method is responsible for toggling the isSelected flag:

changeColor(menuItem){
    // Turn off all selected menu items
    this.menuList.forEach(item => {
        if(item.isSelected){
            item.isSelected = false;
        }
    });
    // Select the clicked menu item
    menuItem.isSelected = true;
}

This way, Angular takes care of all the DOM manipulation. To see this in action, you can check out this Plunker demo (https://plnkr.co/edit/NEnzKZ84M85mErYGLE1Y?p=preview)

Answer №2

If you want to change the background color using Angular ngStyle, follow these steps:

<li id="menu_button" (click)="myStyle = {'background-color': #816587}" [ngStyle]="myStyle">

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

Toggle Visibility of Div Based on Matching Class Name When Clicked

Just delving into the world of jQuery and could use some guidance. Is there a way to show a div with a matching class when a specific button is clicked? For example, clicking on a button with the class '.project1' should display the corresponding ...

Having trouble retrieving the URL from the router in Angular 2?

Whenever I try to access the URL using console.log(_router.url), all it returns is a / (forward slash). Here is the code snippet in question: constructor( private el: ElementRef, private _auth:AuthenticationService, @Inject(AppStore) private ...

Having trouble with CSS values not being applied to dynamically injected HTML div elements in Angular 4?

Link to Codepen My Angular calendar application runs smoothly without any errors. However, I am encountering an issue where the CSS styles are not being applied to the page. When I implemented this separately, everything worked fine. But as soon as I inc ...

Effortlessly apply CSS styles to multiple cached jQuery variables without redundancy

Hey there, I've got this piece of code written in Javascript for a classic ASP page. Since there are no CSS classes defined, everything is handled within the Javascript itself. var $a= $('#a'), $v= $('#v'), $s= $('#s'), ...

AngularJS: Default value causes dropdown menu text to not display

I am facing an issue with my select menu. <select id="dd" ng-show='data != null' ng-model='search'></select> Initially, I set the filter to display only USA by default. $scope.search = 'United States of America' ...

Tips for aligning images inside tab content areas

While using an "accordion" jQuery to show a contact list, I have encountered a challenge that may seem simple to someone experienced in this. Here is the code snippet: <!doctype html> <html lang="en> ... (Code continues) I am looking to add ...

Obtain the content of a clicked item on the following page using NextJs

I am currently working on a nextjs app that displays a list of 10 movies on the homepage, each with a Button / Link that leads to a specific page for that movie where all its content is shown. Initially, I tried adding the movie id to the Link like this: ...

Achieving a centrally aligned flex container with left-aligned flex items

My goal is to center the flex items, but when they go onto a second line, I want item 5 (from image below) to be positioned under item 1 instead of centered in the parent container. https://i.sstatic.net/GhD1E.png Here's a sample of my current setup ...

Determining the type relationship between two generic types when using a union

Here is the code snippet defining a React component using react-hook-form: import { type FieldPath, type FieldValues, type FieldPathValue, } from "react-hook-form"; interface FormControlRadioBoxProps< TFieldValues extends FieldValue ...

Why does the IMG keep loading every time the web page is refreshed?

I am experiencing an issue with my html page where the background images are not reloading when I refresh the page, but the logo image is. The background images are called through an external CSS file, while the logo is used with an <image> tag. Wh ...

Exploring the Potential of JSP in Form Submissions

Here's a OCWCD question that I encountered: <form action="sendOrder.jsp"> <input type="text" name="creditCard"> <input type="text" name="expirationDate"> <input type="submit"/> </form> The question based on the ...

What is preventing the buttons from filling the entire space of the parent element in this case?

https://i.stack.imgur.com/kbiWi.png I'm trying to figure out how to make the Repos and Stars buttons fill the entire height of their parent container, similar to the Github icon. Unfortunately, the code below is not achieving this effect. I attempted ...

Perform mathematical operations on numbers using jQuery based on their index

Trying to manipulate numbers in the HTML with this less-than-ideal code. The display starts like this at the beginning: 1/ 6 And ends up like this at the final index: 6/ 6 Utilizing this in conjunction with pageslide.js as a workaround for the default ...

Ensure that jquery.load is executed before the HTML content is loaded

Recently, I encountered a situation where I had a bootstrap navbar stored in a separate file, specifically named navbar.html. I utilized Jquery.load() to load this navbar into my HTML page. At the bottom of my HTML page, I included the following code: &l ...

Universal in Angular is malfunctioning

As a newcomer to Angular 4, I am looking to create an Angular app that is SEO friendly and supports Angular Universal (with the --universal flag after ung new or ung init). I have successfully created an Angular Universal app. However, when running the p ...

What other technique can I use to replace the creation of a jquery division?

I`m relatively new to all things related to web technologies and I am currently practicing and learning about them. On my practice page, I've experimented with various elements, including changing div heights based on the viewport height. Here's ...

Creating dynamic checkboxes and dropdown menus in Angular 8 by fetching data from an API

Take a look at my Stack Blitz project: here I am trying to achieve two things: hide the dropdown if the divisions are empty, and set the default value of the dropdown to the first one in the list. Can anyone guide me on how to accomplish this? Your help ...

Angular-ui-bootstrap-tabs feature smooth transitions when switching between tabs, but lacks animation when moving

Just made some updates to an example by user @austin Encountering an issue when trying to transition backwards (from tab3 to tab2), but it works fine when transitioning forward. I'm not sure what I'm missing here, so any help would be appreciate ...

Refresh DataTable while making a fetch request

Here is the HTML code snippet where I want to apply DataTable: <div id="reportrange" style="background: #fff; cursor: pointer; padding: 5px 10px; border: 1px solid #ccc;"> <span></span> </div> <table id=" ...

Adjust HTML table cell height to dynamically match content and align to top

I am currently working on creating a table layout where the left column adjusts its height based on content, while the right column needs to have a fixed height of 300. <table border="1" cellspacing="0" cellpadding="0"> <tr> <td>&a ...