Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

313
Views
How to cleanly change the style of a single element on click with a different color for each element of an ngFor with angular

i'm starting with angular and my question is quite simple. (I'm sure there is an answer on the internet but I don't know how to formulate my question simply)

here is my component

I just want to change the color of the button on the right side like this and when i click on another one the first one get back to normal and the actual change color

Here is the code of my component :

<div class="container-scrap">
<div class="legend">
    <div class="color-sample" [ngStyle]="{'background-color': scrap.color}"></div>
    <p>{{scrap.scrapName}}</p>
</div> 
<div>
    <button (click)="selectType($event, scrap.color)" class="legend-button" [disabled]="!availableInput"></button>
</div> 

I'm calling my component this way :

<app-scrap-list *ngFor="let scrap of scrapList" [scrap]="scrap" [availableInput]="availableInput"></app-scrap-list>

Currently i'm using only some simple javascript instruction and the code of my selectType($event, scrap.color) is :

  selectType({target} : any, color : string): void {
    this.scrapListService.setSelected(this.scrap.id);

    //(document.querySelectorAll(".legend-button") as HTMLCollectionOf<HTMLElement>).forEach(btn => btn.style.backgroundColor = "white")
    const legendButton = Array.from(
      document.getElementsByClassName('legend-button') as HTMLCollectionOf<HTMLElement>
    );
    
    legendButton.forEach(btn => {
      btn.style.backgroundColor = 'whitesmoke';
      btn.style.borderColor = 'grey';
    });
    

    target.style.backgroundColor = color;
    target.style.borderColor = color;
    target.style.backgroundImage = "url(../../assets/ajout_rectangle_active.png)";
  }

Is there a better and simple way to do it using angular properties like ng-class, ng-style or others?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Your code looks like have some old fashoned javascript.
For a better approch, maybe Render2 could be more useful.
In short: Render2 is used to change style and other properties to a element.
You could create a custom component that defines the button.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!