Joe Berthelot
Joe Berthelot

Reputation: 735

Dynamic CSS Classes in Angular2+

HTML:

<div *ngFor="let record of lift" class="list-lifts" [class.showLifts]="isBtnActive">

Component:

isBtnActive: boolean = false;

toggleClass() {
    this.isBtnActive = !this.isBtnActive;
  }

CSS:

.list-lifts {

  &:not(:first-of-type) {
    margin-top: -11px !important;
    display: none;
  }
}

.showLifts {
  display: block !important;
}

// I need something like this to be built in the view:
.ValueshowLifts {}

The toggleClass() function toggles the CSS class .showLifts on the click of a button. This works great.

The issue is, I need the class .showLifts to have a dynamic name and I'm not sure what the syntax is to produce it. For logical reasons, here's an example:

[class.{{ record.name }}showLifts]="isBtnActive"

But of course this isn't valid syntax.

Upvotes: 12

Views: 39099

Answers (4)

jason_hamp
jason_hamp

Reputation: 136

As others have mentioned you can use [ngClass]. An answer was posted here:

Dynamic classname inside ngClass in angular 2

But I wanted to mention that if you're using CSS to only hide or show elements, then instead you can use *ngIf or [hidden], depending if you want the element in the DOM or not.

Upvotes: 10

ganesh kalje
ganesh kalje

Reputation: 3182

<div class="form-group label-floating" 
    [ngClass]="{'is-empty': true, 'second-class' : true}"></div>

Upvotes: 3

Ketan Akbari
Ketan Akbari

Reputation: 11257

Try this:

<div *ngFor="let record of lift; ; let i=index" class="list-lifts" 
[ngClass]="{'showLifts': isBtnActive}">

Or you can Use: *ngIf

*ngIf="expression" (e.g. *ngIf="i!=0" or *ngIf="i==0")

Upvotes: -1

Raj
Raj

Reputation: 505

You can leverage ngClass directive here

[ngClass]="showLiftsClass"

Inside your code you can dynamically add css classes to it as follows,

showLiftsClass = {
      'record1showLifts' : true,
      'record2showLifts' : false,
      'record3showLifts' : false,
      'record4showLifts' : false
      ...
}

You can have single or multiple classes as a true. Value true will add the class to the DOM element.

Upvotes: 7

Related Questions