0

I have a looped list. I have to add class active when any block is clicked. I am not sure how to do it using [ngClass]. Please help me.

It is HTML code:

<div *ngFor="let cell of myData">
    <div class="list-header">
        <label>{{ cell.name }}</label>
    </div>
    <div class="list-group">
        <a class="list-group-item list-group-item-action d-flex" *ngFor="let unit of cell.array" (click)= "onClick()" [ngClass]="{'active': this.active}">
            <label>{{ unit }}</label>
        </a>
    </div>
</div>

my TS code:

myData = [
{
  'name': 'abc',
  'array': ["asass","From Mac","New", "test 1", "test 10", "test 2", "test 3", "test 4", "test 5", "test 6", "test 7", "test 8", "test 9" ]
},
{
  'name': 'all types and options',
  'array': ['Camera','del TYPE','Fan','hardware','icons','mobile','new asset type']
},
{
  'name': 'am cat',
  'array': ['am type','camera','new 423423']
},
{
  'name': 'cat with no asset types, dec added',
  'array': ['camera']
},
{
  'name': 'cat with one asset type',
  'array': ['camera']
},
{
  'name': 'colors',
  'array': ['pink', 'yellow']
}
];
Pingolin
  • 3,161
  • 6
  • 25
  • 40

2 Answers2

0
<div class="my_class" (click)="clickEvent()"  
    [ngClass]="active ? 'success' : 'danger'">                
     Some content
</div>

active: boolean = false;
clickEvent(){
    this.active = !this.active;       
}
Harsh Manvar
  • 27,020
  • 6
  • 48
  • 102
0

template:

<div *ngFor="let cell of myData">
      <div class="list-header">
        <label>{{ cell.name }}</label>
      </div>
      <div class="list-group">
        <a class="list-group-item list-group-item-action d-flex" *ngFor="let unit of cell.array; let i = index" (click)= "cell.selectedIndex=i" [ngClass]= "{ 'active': cell.selectedIndex === i }" >
          <label>{{ unit }}</label>
        </a>
      </div>
    </div>