Search code examples
angularng-class

setActive ngClass angular


Hi i have a problem with a simple angular component, i'm using a reactive form to insert text then i loop the text by using ngFor after i want to set active one element by click but when i click one element all the element reach active class, this is my template. this is the stack blitz link

<form [formGroup]="colorsForm">
  <div>
    <label for="colorName">Color Name</label>
      <input id="colorName" type="text" class="form-control" 
        formControlName="colorName" name="colorName"/>
  </div>
  <button  type="button"  (click)="addCorlo()">ADD</button>
</form>
<div
*ngFor="let color of colorsList; let i = index"
(click)="setActive(color)"
[ngClass]="{'active' : color.i === active?.i}"
>
<div
> ID {{ i }} - color {{ color.colorName }}<button (click)="delete(i)">DELETE</button></div>
</div>

and this is my ts

import { Component, VERSION } from '@angular/core';
import { FormBuilder, FormGroup, FormArray, Validators } from '@angular/forms';


@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Set Active';
  colorsForm: FormGroup; // New Reactive Form
  colorsList: any[] = [];
  active: any;


  constructor(
    private fb: FormBuilder
  ) { }

  ngOnInit() {

    this.colorsForm = this.fb.group({
      colorName: [null]
    });

  }

  addCorlo() {
    if (this.colorsForm.valid) {
      let color = { 
        colorName: this.colorsForm.value.colorName,
      };
      this.colorsList.push(color);
    }
    this.colorsForm.reset();
   }


   delete(i: number) { 
    if (i > -1) {
        this.colorsList.splice(i, 1);
        console.log('ID',i)
        console.log('ARRAY',this.colorsList)
    }
    return this.colorsList;

  }

  setActive(color: any){
    console.log(color);
    this.active = color;
  }


}


Solution

  • [ngClass]="{'active' : color.colorName === active?.colorName}"
    

    This check needs to be specific to colorName.