Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic CSS Classes in Angular2+

Tags:

angular

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.

like image 791
Joe Berthelot Avatar asked Jun 17 '17 06:06

Joe Berthelot


2 Answers

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.

like image 132
Raj Avatar answered Sep 18 '22 18:09

Raj


<div class="form-group label-floating" 
    [ngClass]="{'is-empty': true, 'second-class' : true}"></div>
like image 36
ganesh kalje Avatar answered Sep 19 '22 18:09

ganesh kalje