sanjana
sanjana

Reputation: 131

onCLick list item Add 'active' Class in li and Remove from Siblings -- Angular 8

Default first li will be in active and if click on any li item Add Class 'active' and Remove Class from siblings

public items = [{
    value: 'All',
  },
  {
    value: 'Photos',
  },
  {
    value: 'Video',
  },
];
li .active {
  color: red;
}
<div *ngFor="let item of items" class="nav-li">
  <ul>
    <li class="value" [value]="item.value"><a href="">{{item.value}}</a></li>
  </ul>

</div>

Upvotes: 1

Views: 7802

Answers (4)

elonaire
elonaire

Reputation: 1994

.ts

    public items = [{
        value: 'All',
        active: 'active'
      },
      {
        value: 'Photos',
        active: ''
      },
      {
        value: 'Video',
        active: ''
      },
    ];
    
    changeStatus(index) {
      this.items = this.items.map((item, itemIndex) => {
        index === itemIndex ? item.active = 'active' : item.active = '';
        return item;
      })
    }

.html

<div *ngFor="let item of items; index as i" class="nav-li">
  <ul>
    <li [class]="item.active" (click)="changeStatus(i)"  [value]="item.value"><a href="javascript:void(0);">{{item.value}}</a></li>
  </ul>

</div>

Upvotes: 2

Pardeep Jain
Pardeep Jain

Reputation: 86740

You can save the clicked index in variable and toggle the class dynamically accordingly, as mentioned below -

<div class="nav-li">
  <ul>
    <li *ngFor="let item of items; let i = index" 
    [ngClass]="{'active': selectedItem === i}"
    [value]="item.value" 
    (click)='selectedItem = i;'>
      {{item.value}}
    </li>
  </ul>
</div>

selectedItem = 0;

Working Example

Suggestion - If not required try to iterate the *ngFor on li DOM element instead of DIV but doing so you are repeating div, ul,li elements for each iteration which is costly for the DOM prospective.

Upvotes: 5

Kamaal
Kamaal

Reputation: 61

    **Html**
    <div *ngFor="let item of items; let i=index" class="nav-li">
      <ul>
        <li class="{{selectedIndex==i ? 'active':''}}" [value]="item.value"><a href="#" (click)="selectTag(i)">{{item.value}}</a></li>
      </ul>
    </div>
    
    **Ts**
     selectTag(index){
        this.selectedIndex = index;
      }

**.Css**

.active {
  color: red;
}

Upvotes: 0

aks44
aks44

Reputation: 432

Try this.. Please note that i have removed href from tag.. .html

<div *ngFor="let item of items; let i = index" class="nav-li">
    <ul>
        <li class="value" [ngClass]="getActiveClass(i)" [value]="item.value" 
           (click)="setActiveIndex(i)">
           <a>{{item.value}}</a>
        </li>
    </ul>
</div>

.ts

  var activeIndex;

  setActiveIndex(index) {
    this.activeIndex = index;
  }

  getActiveClass(i) {
    return this.activeIndex == i ? 'active' : '';
  }

.css

.active {
  color: red;
}

Upvotes: 0

Related Questions