What is the best way to assign a class to a clicked element and remove it from the previous one?

Currently, I am utilizing Angular to control the visibility of different divs using the ngIf feature. Below is an example of what I have implemented:

.html

<div class="boxes">
<div class="box" (click)="tabToggle(1)">box1</div>
<div class="box" (click)="tabToggle(2)">box2</div>
<div class="box" (click)="tabToggle(3)">box3</div>
<div class="box" (click)="tabToggle(4)">box4</div>
<div class="box" (click)="tabToggle(5)">box5</div>
</div>

<div *ngIf="showTab == 1" class="box1-content">Lorem ipsum 1</div>
<div *ngIf="showTab == 2" class="box2-content">Lorem ipsum 2</div>
<div *ngIf="showTab == 3" class="box3-content">Lorem ipsum 3</div>
<div *ngIf="showTab == 4" class="box4-content">Lorem ipsum 4</div>
<div *ngIf="showTab == 5" class="box5-content">Lorem ipsum 5</div>

For more information check out this live link: https://stackblitz.com/edit/angular-8reazh?embed=1&file=src/app/app.component.ts

I am exploring ways to add a specific class to the currently selected "box" element. For instance, highlighting the selected box with a blue background while reverting the previous selection back to red when clicking on another box.

Answer №1

Choice 1

To include the styling, insert

[ngClass]="{'current':showTab == 1}
in your HTML code.

Sample code:

<div class="boxes">
<div class="box" (click)="tabToggle(1)" [ngClass]="{'current':showTab == 1}">box1</div>
<div class="box" (click)="tabToggle(2)" [ngClass]="{'current':showTab == 2}">box2</div>
<div class="box" (click)="tabToggle(3)" [ngClass]="{'current':showTab == 3}">box3</div>
<div class="box" (click)="tabToggle(4)" [ngClass]="{'current':showTab == 4}">box4</div>
<div class="box" (click)="tabToggle(5)" [ngClass]="{'current':showTab == 5}">box5</div>
</div>

CSS for the above code:

.current{
   background: blue;
}

Choice 2

You can also utilize [style.background] to achieve similar results.

View functional example

<div class="boxes">
<div class="box" (click)="tabToggle(1)" [style.background]="showTab == 1?'blue':'red'">box1</div>
<div class="box" (click)="tabToggle(2)" [style.background]="showTab == 2?'blue':'red'">box2</div>
<div class="box" (click)="tabToggle(3)" [style.background]="showTab == 3?'blue':'red'">box3</div>
<div class="box" (click)="tabToggle(4)" [style.background]="showTab == 4?'blue':'red'">box4</div>
<div class="box" (click)="tabToggle(5)" [style.background]="showTab == 5?'blue':'red'">box5</div>
</div>

Answer №2

When working with HTML:

<div class="boxes">
<div class="box" (click)="tabToggle(1)" [class.selected]="selectedbox == 1">box1</div>
<div class="box" (click)="tabToggle(2)" [class.selected]="selectedbox == 2">box2</div>
<div class="box" (click)="tabToggle(3)" [class.selected]="selectedbox == 3">box3</div>
<div class="box" (click)="tabToggle(4)" [class.selected]="selectedbox == 4">box4</div>
<div class="box" (click)="tabToggle(5)" [class.selected]="selectedbox == 5">box5</div>
</div>

<div *ngIf="showTab == 1" class="box1-content">Lorem ipsum 1</div>
<div *ngIf="showTab == 2" class="box2-content">Lorem ipsum 2</div>
<div *ngIf="showTab == 3" class="box3-content">;Lorem ipsum 3</div>
<div *ngIf="showTab == 4" class="box4-content">Lorem ipsum 4</div>
<div *ngIf="showTab == 5" class="box5-content">Lorem ipsum 5</div>

If you're writing in TypeScript, include the following code:

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  showTab = 1;
  selectedbox: number = 1;
  tabToggle(index){
    this.selectedbox = index;
    this.showTab =index;
  }
}

In your CSS file, make sure to add this class:

.selected {
  background-color: black;
  color: white;
}

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

In a local setting, the KendoUI chips are displaying without their borders

I recently tested out the code from kendo on StackBlitz and it worked perfectly: https://i.stack.imgur.com/Nrp2A.png However, when running the same code on my localhost, all the styling for the chip is missing: https://i.stack.imgur.com/1pUH9.png The c ...

How can I adjust height without affecting weight in CSS using curly brackets?

Can CSS be used to specifically adjust the height of a curly bracket without changing its thickness? I have been attempting to modify the height of a curly bracket dynamically by adjusting the font-size, but this also alters the weight. Is there a workar ...

Sticky header in an Angular Material table

Using Angular 7 with Angular material design templates, my current result looks like this: https://i.sstatic.net/G4W78.jpg However, I am aiming for a result similar to the following - with a scrollbar under the sticky header. https://i.sstatic.net/WgjVh ...

Text will not be visible within the div container

I'm working on a mobile layout design for my css project. My goal is to have the header and footer remain fixed on the screen while allowing users to scroll through the content in between. I was able to achieve the fixed positioning, but now none of m ...

After applying 'all: unset;' to remove all styles, the CSS hyphens property does not work as expected in Chrome

After applying this CSS code to remove all styles: * { all: unset; display: revert; } The issue arises in Chrome browser where CSS Hyphens are not taking effect. This can be seen with the following example: div { font-size: 3rem; -webkit-hy ...

Is it possible to wait for the conversation to be updated within the Microsoft Bot Framework?

After successfully creating a chatbot for Messenger, I decided to develop my own interface. However, I encountered some challenges with managing the replies. Despite using the Microsoft BotFramework and being able to send and receive messages, I struggled ...

Smoothly scroll down to the bottom of the page with a jQuery button using the anchor

Recently, I've been working on setting up a navbar with buttons that smoothly scroll down to specific sections when clicked. However, as a beginner in jquery, I'm having some trouble figuring out how to make it work seamlessly. Can anyone guide ...

How can you hide specific elements in HTML/CSS based on window size without relying on media queries?

How can I create an HTML/CSS toolbar where specific elements disappear completely when the browser size is decreased, similar to how the favorites bar functions in most browsers? The toolbar should be able to display a varying number of items. In this cas ...

What are some effective ways to restrict users from downloading the HTML template from a demo site?

I'm looking to start selling HTML templates online, but I'm realizing that creating a demo page may lead users to simply download the template without purchasing it. How do other sellers prevent this from happening? What strategies can ...

Looking to implement a collapsible feature on a webpage using PHP, JavaScript, and HTML

I am looking to enhance the appearance of a section in a table by making it collapsible. The code snippets below are from editor_transdata.php <script language="javascript> function toggle_message(type) { document.getElementById("div_message").s ...

Steps for making a button with both an image and text:

I am in the process of designing a basketball-themed website and I am looking to incorporate custom icons/buttons that link to various pages on the site. My vision is to have a unique button that features a circular image with accompanying text below it. ...

CSS not working when attempting to override Angular (13) Material file

In my Angular (13) application with Material, I have developed a CSS file specifically for overriding certain Material styles. This CSS file is imported into the styles.scss file as the last line. However, despite importing the external file, the CSS def ...

When rails code is placed within haml tags, it results in generating empty spaces within the HTML tags of browsers

Every time a rails variable is nil (or when using rails code (as seen in the third code example)), my html displays a string of empty characters. new.html.haml %h1.editable.editable_title_field{:contenteditable => 'true', :placeholder => ...

Optimizing Angular for search engines: step-by-step guide

Regarding Angular SEO, I have a question about setting meta tags in the constructors of .ts files. I have implemented the following code: //To set the page title this.titleServ.setTitle("PAGE TITLE") //To set the meta description this.meta.addTag ...

Gradient that runs in a straight line from opposite ends

Is there a way to apply linear gradients from both the top and bottom to create smoother lines when text is scrolled? I was able to achieve a linear gradient at the bottom using this code: <div className="vsebina" style={{WebkitMaskImage:&apo ...

The Canvas drawn using JavaScript is not being resized and painted correctly on Safari mobile and Firefox mobile browsers

I created an HTML page that features a canvas element where I am drawing a roulette using JavaScript After checking the CanIuse website, I learned that canvas functionality is supported in Firefox 68 and Safari 4 to 13 <!DOCTYPE html> <html> ...

Is there a way to customize the dot in a JavaFx RadioButton?

Hello fellow coding enthusiasts, I am looking to find out how I can customize the color of a RadioButton dot. I want to have 3 RadioButtons, each with a different color to represent a state. Do I need to use CSS for this task? If so, could someone please ...

Dealing with Angular error interceptor and handling multiple occurrences of 401 responses

I'm currently working on implementing a refresh token feature in my Angular frontend to handle expired access tokens. The issue I'm facing is that upon reloading the page after token expiration, multiple requests are sent to the backend simultane ...

What is the best way to construct the following layout with columns in Bootstrap?

My approach involved dividing the content into two equal columns using col-md-6. Each of these was further split into 3 columns using col-md-4. However, I faced an issue regarding achieving consistent spacing between columns on the right side. https://i.s ...

Measuring the frequency of API calls through HttptestController

I need to track the number of times an API is being called, and I am using HttpTestingController to achieve this. When const req = httpMock.expectOne('/api/getrecords'); fails it('should return one object', () => { var dummyO ...