Search code examples
angularangular2-mdl

Angular2 applying dynamic css class fails


I have an expansion panel group and I am trying to appy a css class to the active panel:

<mdl-expansion-panel-group>
    <mdl-expansion-panel *ngFor="let task of tasks" [ngClass]="{'active': task.id == selectedTask}">
        <mdl-expansion-panel-header>
            <mdl-expansion-panel-header-list-content><h6>{{task.what_task}} {{task.id}}</h6></mdl-expansion-panel-header-list-content>
        </mdl-expansion-panel-header>
        <mdl-expansion-panel-content>
            <mdl-expansion-panel-body>

                <button mdl-button mdl-button-type="raised" mdl-colored (click)="selectTaskToEdit(task)">
                    Edit
                </button>

            </mdl-expansion-panel-body>
        </mdl-expansion-panel-content>
    </mdl-expansion-panel>
</mdl-expansion-panel-group>

css class active has a background color set to say yellow. In my component I am printing console.log(this.selectedTask==task.id) which comes out true, however my class is not being applied.

My component:

  selectTaskToEdit(task){

    this.task=task;
    this.selectedTask=task.id;
    console.log(this.selectedTask==task.id)
  }

and css:

.active {
  background-color: yellow;
}

Am I doing anything wrong?

UPDATE: I could solve it using [style.background-color]="task.id == selectedTask ? 'yellow': null " however I would like to know if there is a correct way of doing with ngClass


Solution

  • [style.background-color]="task.id == selectedTask ? 'yellow': null"

    or

    [class.active]="task.id == selectedTask"

    is the only way to make it, because mdl-expansion-panel has own host class expressions, which overrides yours [ngClass].

    Here is the example plnkr.