Angular - updating the icon color upon clicking

I have a table that lists items, each with an icon next to it. I want to be able to click on the icon and change its color individually. Currently, clicking on any icon only changes the color of the first one.

<table class="table table-borderless" style="background-color: #CCE4E9">
    <tbody>
        <tr *ngFor="let content of acts">
            <td style="font-size: 14px;" *ngIf="content.status == 2;">{{content.description}}
            </td>
            <td>
                <button id="addToSummary" class="mdc-icon-button material-icons" style="color: #FFFFFF;"
                    (click)="addToSummary()">grade</button>
            </td>
        </tr>
    </tbody>
</table>

addToSummary(){
  document.getElementById("addToSummary").style.color = "#3DA2DA";

}

https://i.sstatic.net/ajMMv.png

What steps do I need to take to change just one of them?

Answer №1

The solution you are currently using is ineffective because the getElementById function only retrieves the first element with the specified id. This method of querying the DOM is not typically recommended in Angular.

Instead, consider updating your button definition to something similar to this:

<button class="mdc-icon-button material-icons" [style.color]="content.isSelected ? '#3DA2DA' : 'FFFFFF'" (click)="addToSummary(content)">grade</button>

Additionally, adjust your addToSummary method as follows:

addToSummary(content){
    content.isSelected = true;
}

Here's a breakdown of how this works:

  • Each item in the acts array includes an isSelected property
  • When this property is true, the star icon turns blue
  • In the addToSummary method, we update the isSelected property to true
  • We adopt the 'Angular way' by utilizing [style.color] which allows for a simple expression to switch between white and blue colors

Answer №2

One way to approach the problem is as follows:

<table class="table table-borderless" style="background-color: #CCE4E9">
   <tbody>
        <tr *ngFor="let content of acts; let i = index;">
           <td style="font-size: 14px;" *ngIf="content.status == 2;"> 
              {{content.description}}
           </td>
           <td>
               <button id="addToSummary" [ngClass]="['addToSummary', i]" class="mdc-icon-button material-icons" style="color: #FFFFFF;"
                (click)="addToSummary(i)">grade</button>
           </td>
        </tr>
  </tbody>
</table>

addToSummary(i){
     let className = "addToSummary " + i;
     document.getElementByClassName(className).style.color = "#3DA2DA";
}

Answer №3

Manipulating the DOM can be achieved using a Renderer

import { ElementRef, Renderer2} from '@angular/core';

constructor(private elRef: ElementRef, private renderer: Renderer2) { }

addToSummary() {
    let element = this.elRef.nativeElement.querySelector('#addToSummary');
    this.renderer.setStyle(element, 'color', '#3DA2DA');
}

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

Issues with Cloud9 Angular and NodeJS connecting to API on a separate port of the same server

I am currently utilizing an AWS Cloud9 IDE for my project. Angular is running on port 8080, while my NodeJS (with Express) server is running on port 8081. In my Node app.js file, I have set up CORS headers as follows: const app = express(); app.use(expre ...

Parent Class implementation for dynamic loading of components

I have been working on creating a new code for dynamic component loading using a parent-child relationship. The child component is set to override the parent and will be used for dynamically loading components. I found this useful link that guided me throu ...

Next.js: Specify HTTP response code

I am working on a Next.js v12 application that is written in TypeScript. Within this application, I have created a custom error page called _error.tsx to provide a user-friendly experience for various errors such as 410, 404, and more. The issue I am faci ...

Removing AWS-CDK Pipelines Stacks Across Multiple Accounts

Currently, I am utilizing pipelines in aws-cdk to streamline the process of automating builds and deployments across various accounts. However, I have encountered an issue where upon destroying the pipeline or stacks within it, the respective stacks are ...

Issue with MongoDB $push within an Array of Arrays: The shorthand property 'elements' does not have a value available in scope

I am encountering an issue while trying to insert data into Elements in MongoDB using TypeScript. Any suggestions on how to resolve this problem? Attempt 1 Error: I am receiving an error message stating "No value exists in scope for the shorthand property ...

The result of the Aggregate Function in Slickgrid does not update or change according to the data edited inline in Slickgrid

Utilizing angular slick grid version 4.3.1 to display a data list. The configuration includes aggregate function calculation for columns when data is grouped by a specific field. However, if a column used in the aggregate function is edited, the result doe ...

Expanding code lines beyond 80 characters in Visual Studio Code with TSLint integration

I am utilizing TypeScript alongside TSLint and Prettier within Visual Studio Code for developing a React Native App. Despite my efforts to set up my editor to automatically wrap the code per line at 100 characters, it consistently reverts back to 80 chara ...

The color rendering of objects in the b3dm file is not displayed correctly by three.js

Currently, I am working on converting a file with a .b3dm extension to a .glft and then displaying it by loading it in three.js. For guidance, I am referring mainly to an interesting article. However, I seem to be facing an issue where the object is only ...

What is the best way to consistently and frequently invoke a REST API in Angular 8 using RxJS?

I have developed a REST API that retrieves a list of values. My goal is to immediately invoke this API to fetch values and store them in a component's member variable. Subsequently, I plan to refresh the data every five minutes. Upon conducting some ...

Troubleshooting Angular error encountered during the execution of the 'ng build --prod' command

While developing my Angular application, I encountered an issue when using the ng build --prod command. Surprisingly, everything was working fine with ng serve. I am struggling to figure out what the problem could be. ERROR in: Unable to locate resource a ...

Trouble with modifying a cell in a TypeScript office script

Hello everyone. I am in need of a code that can track which cells are active or selected, and then block them once a user is no longer interacting with them. I understand that there may be some issues, especially if the user selects a cell but does not ma ...

Using a custom validator in Angular that accepts an array as input

My special code: <input mdInput [mdAutocomplete]="auto" [(ngModel)]="formData.areaName" (keyup)="updateFilteredAreas(formData.areaName)" class="form-control {{areaName.errors ...

Experiencing Typescript errors solely when running on GitHub Actions

I've been working on a React+Vite project with the Dockerfile below. Everything runs smoothly when I execute it locally, but I encounter errors like Cannot find module '@/components/ui/Button' or its corresponding type declarations and error ...

Setting default values for HOCs in React

If I have a higher order component structure like this: interface MyHOCInterface { title: string } export function wrapMyHoc<T extends MyHOCInterface>( Component: React.ComponentType<T>,) { return class extends React.Component<T> { ...

Struggling with creating a generic TypeScript structure?

My goal is to manipulate data structured like this: const exampleState = { elements : { element1: { values: { value1: 10, value2: 10, }, elementDetails : { detail1 : { values: { value1: ...

Issue: Angular 14 - Validators Not Resetting in Nested FormGroup

I am currently working on implementing a nested FormGroup. However, I have encountered an error when attempting to reset the form. Here is the structure of the form: form: UntypedFormGroup; this.form = this.fb.nonNullable.group({ f1: [''], f2: ...

Display a loading GIF for every HTTP request made in Angular 4

I am a beginner with Angular and I am looking for a way to display a spinner every time an HTTP request is made. My application consists of multiple components: <component-one></component-one> <component-two></component-two> <c ...

ERROR: Module 'app/home/home.module' Not Found - Unhandled Promise Rejection

Currently attempting to implement lazy loading of Angular 2 modules using the router, encountering the following error: error_handler.js:50 EXCEPTION: Uncaught (in promise): Error: Cannot find module 'app/home/home.module' Have tried various ...

Leveraging TypeScript Declarations for an External JavaScript Library

Struggling to find clear documentation on how to properly use the ALKMaps JavaScript library in my Ionic application. I created a local npm module with an alkmaps.d.ts file, but I can't seem to import it into my Angular code without encountering error ...

Tips for effectively highlighting search text within HTML content without causing any issues

I am in search of a solution that can assist me in searching for specific terms within an HTML string while also highlighting them. I have the ability to remove the HTML content from the string, but this poses the problem of losing the context of the origi ...