0

I want to add one class or another with a click event, I'm using the angular ngClass, but it doesn't work for me. When you click on the "li" element, it calls a function that changes the value of the "isExpandedConectivity" variable, but does nothing.

Component.html:

 <li class="nav-item" (click)="changeCollapsed()" aria-controls="collapseUsuarios">
            <a href="#" class="nav-link">
                <span class="w-20px text-center mr-2">
                    <i class="fad fa-analytics"></i>
                </span>
                Conectividad
                <span class="w-100">
                    <i [ngClass]="'fad float-right isExpandedConectividad ? fa-chevron-down : fa-chevron-right"></i>
                </span>
            </a>
            <ul id="collapseConectividad" [collapse]="!isCollapsedConectividad" [isAnimated]="true" class="nav flex-column ml-5">
                <li class="nav-item">Tareas</li>
                <li class="nav-item">Diario</li>
            </ul>
        </li>

Component.ts:

export class SidebarComponent {
  isCollapsedTrabajo = false;
  isCollapsedUsuarios = false;
  isCollapsedConectividad = false;
  isExpandedConectividad = false;

  changeCollapsed(): void{
    this.isCollapsedConectividad = !this.isCollapsedConectividad;
    this.isExpandedConectividad = !this.isExpandedConectividad;
    console.log(this.isExpandedConectividad);
  }
}
2
  • I think it may be just [class], that works for me at least Commented Sep 9, 2019 at 14:53
  • 1
    also you have an unmatched: ' it looks like Commented Sep 9, 2019 at 14:58

3 Answers 3

4

You can separate out the statically applied classed and dynamically applied classes as such -

<i class="fad float-right" [ngClass]="isExpandedConectividad ? 'fa-chevron-down' : 'fa-chevron-right'"></i>

Check comparable StackBlitz here

You can check the usage of ngClass here. In your case, the boolean was being evaluated under single quotes - ' '

Sign up to request clarification or add additional context in comments.

Comments

1

I always do the following:

Html:

 <button (click)="onClick()">

TS:

activeClass: boolean;    
onClick() {this.activeClass = !this.activeClass}

And again in Html:

<div [ngClass]="{cssClass1: activeClass, cssClass2: !activeClass}">

You can add as many classes as you wish allthough a boolean won't be enough then ^^

Comments

0
[class.yourclassename]="isExpandedConectivity" 

and if this condition is true, the class will be added

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.