Angular 4 allows for dynamically applying the active class to a clicked button, enhancing interactivity

Issue:

<button *ngFor="let button of buttons" [ngClass]="{'active': isClicked}" (click)="isClicked = !isClicked"

Description:

A total of 10 buttons are displayed on the screen.

When I click on button number 1, each button receives the class ".active".

Preferred Outcome:

Upon clicking button number 1: it should receive the class ".active".

Upon clicking button number 3: it should receive the class ".active".

Upon clicking button number 6: it should receive the class ".active".

Result:

Button 1, Button 3, and Button 6 will be assigned the class ".active"

Any suggestions on how to achieve this?

Find Plunker demo here: https://plnkr.co/edit/lX3DjN46STmo6gfBkPCc?p=preview

Answer №1

Simply utilize a temporary array

<button *ngFor="let button of [1,2,3,4]; let i = index" [ngClass]="{'active':isClicked[i]}" (click)="isClicked[i] = (isClicked[i]? false :true )">button</button>

within the component public isClicked = [];

working fiddler --> https://example.com/edit/AbCdE1FgHiJkLmNoPqRs?p=preview

Trust this explanation helps!!

Answer №2

By utilizing (click)="isClicked = !isClicked", you are assigning a unique individual isClicked property to each button within the component instead of sharing it among all buttons. To achieve this, enhance your buttons array to contain objects:

buttons = [
    { text: 'item1', isClicked: false },
    { text: 'item2', isClicked: false },
    { text: 'item3', isClicked: false },
    // ...
]

This approach ensures that every button possesses its own distinct isClicked property, allowing you to implement it in this manner:

<button *ngFor="let button of buttons" [ngClass]="{'active': button.isClicked}" (click)="button.isClicked = !button.isClicked">
    {{ button.text }}
</button>

Explore the updated plunker example for reference.

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

Could you please tell me the type that is returned by the createClient function?

Despite being a TS newbie, I have been delving into writing small services using TS. Recently, I've been developing a CLI tool that leverages the power of node-redis, which is an exceptional redis client. The burning question on my mind is regarding ...

The FireBase getToken function with the forceRefresh set to true has failed to perform as expected

I encountered a problem with this code snippet from Firebase when trying to run it in Angular 2 CLI. It gives an error of 'unreachable code'. How can I fix this issue and get it to work properly? firebase.auth().currentUser.getToken(/forceRefres ...

The value of a checkbox in Angular 10 is coming out as undefined

Within my component, I set up the formGroup as shown below: constructor(private apiService: ApiService) { this.form = new FormGroup({ product: new FormControl(), shops: new FormGroup({}) }); } When selecting a vendor from a drop-do ...

Angular - Show a table of items from a given list

I recently started using Angular and I'm facing a challenge in displaying multiple tables based on a list of values. Each rule refNo should have its own separate rule conditions table displayed sequentially. Currently, all the tables are showing the s ...

Encountered an issue with a module not being found while trying to install a published React component library that is built using Rollup. The error message states:

In my latest project, I have developed a React component library called '@b/b-core' and used Rollup for building and publishing to the repository. When trying to install the library in a React app, an issue arises where it shows Module not found: ...

The combination of [(ngModel)] and name is not compatible with angular's ng-autocomplete feature, causing it to malfunction

I'm currently integrating ng-autocomplete with Angular 8, and encountering an issue. Here is the code snippet: HTML: <div class="field"> <label class="label">Nombre del condominio:</label> <div class="control"> ...

Next.js 14 useEffect firing twice upon page load

Having an issue with a client component in next js that is calling an API twice at page load using useEffect. Here's the code for the client component: 'use client'; import { useState, useEffect } from 'react'; import { useInView ...

cdkDropList does not function properly when used with ng-template in a dynamic component list

Exploring the new Drag&Drop features introduced in Angular Material 7, I am dynamically generating components using ng-template. <div cdkDropList (cdkDropListDropped)="dropLocal($event)"> <ng-template #components></ng-templat ...

Guide to defining font style in vanilla-extract/CSS

I'm trying to import a fontFace using vanilla-extract/css but I'm having trouble figuring out how to do it. The code provided in the documentation is as follows: import { fontFace, style } from '@vanilla-extract/css'; const myFont = fo ...

What could be causing the issue where only one of my videos plays when hovered over using UseRef?

I'm currently working on a project where I have a row of thumbnails that are supposed to play a video when hovered over and stop when the mouse moves out of the thumbnail. However, I've encountered an issue where only the last thumbnail plays its ...

Retrieve a user by their _id, remove a user using their _id, and modify a user based on their _id using Next.js 14, utilizing Typescript

I'm currently troubleshooting three request methods that are not functioning properly: GET, UPDATE, and DELETE for a user by _id. When I try to run these requests in the browser or postman, I receive a "no page found" error in the API call. The rout ...

Expand the ApiGateProxyEvent category from aws-lambda

Looking to enhance the ApiGateProxyEvent of aws-lambda in d.ts. Initial attempts replaced the entire APIGatewayProxyEvent instead of extending it as intended. declare namespace AWSLambda { interface APIGatewayProxyEvent { body: any; user: any; ...

How to retrieve cookie value from callback response in Angular?

There are two domains: Angular Application: samlapp.domain.com Node Application: samlapi.domain.com When Node calls the callback with the cookie, it redirects to the samlapp application (samlapp.domain.com/landing) Concern: How can I retrieve the cook ...

Transform the CSS to a Mat-Form-Field containing a search box within it

I am currently working with Angular, Angular Material, and SCSS for my project. Here is the front-end code snippet that I am using: <mat-form-field class="custom-form-field" style="padding-top: 5px;padding-bottom: 0px; line-height: 0px; ...

The correct method for handling arrays with overlapping types and narrowing them down again

When working with arrays containing different types in TypeScript, I often encounter issues with properties that are not present on all types. The same challenge arises when dealing with various sections on a page, different user roles with varying proper ...

An error occurred when attempting to access data within a variable that is undefined, resulting in a TypeError at the errorHandler function

Every time I attempt to send a post, patch, or put request, I keep getting this error. However, there are no issues with get requests. TypeError: Cannot read properties of undefined (reading 'data') at errorHandler (/home/joe/Documents/mypro ...

Developing a REST API for a component with 18 interconnected elements

Currently, I am developing a REST API to expose a table to an Angular frontend, and I've encountered a unique challenge: The data required for display is spread across 10 different tables besides the main entity (referred to as "Ticket"). Retrieving t ...

Is it feasible to broaden an interface in Typescript without including a specific type?

import React from "react"; interface a_to_e { a?: string; b?: string; c?: string; d?: string; e?: string; } interface a_to_e_without_c extends a_to_e { // I want to include properties a~e except for c } function Child(props: a_to_e_without_c ...

Tips for integrating material icons into your project

Having some trouble using Outlined material icons in my application. Struggling with the import process and can only access the normal filled icons instead of the outlined ones. I would like to incorporate outlined icons similar to those shown in this exam ...

Using Angular2, summon numerous ajax requests and then patiently wait for the results

I'm facing an issue with my Angular code. Here are the functions I've been working on: private callUserInfo(): any { this.isLoading = true; return this._ajaxService.getService('/system/ping') .map( result => { this.user ...