0

I have a bootstrap list where I show a list of Dashboards. By default one of the Dashboard which starts with some name must be selected by default, by adding a css class to existing class attribute something like below.

<a *ngFor="let user of userModel" class="list-group-item list-group-item-action active">{{user.dashBoardName}}</a>

the class active of class attribute of tag must be added only if the dashBoardName is any string other wise it must be like below

<a *ngFor="let user of userModel" class="list-group-item list-group-item-action">{{user.dashBoardName}}</a>

How can we do that using Angular. By the way I am new to the Angular stuff though.

Hirein
  • 135
  • 5
  • 20
  • You can add a classname depend of the router. Please take a look at [Angular Router and Active Links](https://angular.io/guide/router#active-router-links) – Emilien Mar 23 '20 at 14:53
  • Take a look at [`NgClass`](https://angular.io/api/common/NgClass). – pzaenger Mar 23 '20 at 14:55

2 Answers2

0

Use ngClass directive

<a *ngFor="let user of userModel" class="list-group-item list-group-item-action" [ngClass]="user.dashBoardName === 'activeUser' ? 'active' : ''">{{user.dashBoardName}}</a>

Here I check against a constant literal 'activeUser'. You could also replace it with a variable defined in the controller. Then use the variable name without the single quotes.

ruth
  • 29,535
  • 4
  • 30
  • 57
0

You can simply use [class.xxx] directive with your active class name, as below :

<a *ngFor="let user of userModel" [class.active]="user.dashBoardName === 'activeDashboard'" class="list-group-item list-group-item-action">{{user.dashBoardName}}</a>

This directive will add active class name if condition is true.

You can also move your logic inside a method of your component, to keep your template simple :

in component.ts :

isActive(user: User) {
  return user.dashBoardName === 'activeDashboard';
}

in template.html:

<a *ngFor="let user of userModel" [class.active]="isActive(user)" class="list-group-item list-group-item-action">
Thierry Falvo
  • 5,892
  • 2
  • 21
  • 39