简体   繁体   中英

Angular 4 - Select clicked list item

I have list items as follows in below code snippet. On mouse click I would like to select that item (add 'active' class and deselect if any other items (siblings) selected by remove'active class. this is my nav-bar.component.html

  <li routerLink="/dashboard">
    <a [ngClass]="{'active-menu': selected == 'dashboard'}" (click)="selectClass('dashboard')" ><i class="fa fa-dashboard fa-3x"></i> Dashboard</a>
  </li>
  <li routerLink="/ui" >
    <a [ngClass] ="{'active-menu': selected == 'ui'}" (click)="selectClass('ui')"><i  class="fa fa-desktop fa-3x"></i> UI Elements</a>
  </li>
  <li routerLink="/blank"  (click)="selectClass('blank')">
    <a [ngClass] ="{'active-menu': selected === 'blank'}"><i class="fa fa-square-o fa-3x"></i> Blank Page</a>
  </li>

And this is my nav-bar.component.ts file

export class NavBarComponent implements OnInit {
  selected: string;
   constructor() {}
   ngOnInit() {  }
   selectClass(selected: string) {
   this.selected = selected;
   console.log(this.selected);
 }
}

the active-menu class will be added when i click the list second time. don't whats wrong with my code. but in console, it prints the string correctly.

Better way is to use inbuilt directive routerLinkActive for adding active classes to the current route and use routerLink in a instead of li .

<li routerLinkActive="active-menu">
    <a routerLink="/dashboard"><i class="fa fa-dashboard fa-3x"></i> Dashboard</a>
</li>

Your code is working properly on my machine. Have you tried using class binding eg

<li routerLink="/dashboard">
 <a [class.active-menu]="selected == 'dashboard'" (click)="selectClass('dashboard')" >
 <i class="fa fa-dashboard fa-3x"></i> Dashboard</a>
</li>

The other way to handle your case is by using the routerLinkActive directive. In your example, we can format the links in the following way.

<li routerLink="/dashboard" routerLinkActive="active-menu">
 <a><i class="fa fa-dashboard fa-3x"></i> Dashboard</a>
</li>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM