Home > Net >  Angular - is it possible to toggle more than one CSS class on different conditions?
Angular - is it possible to toggle more than one CSS class on different conditions?

Time:05-02

I'm trying to toggle two CSS classes using different conditions:

  <div *ngFor="let year of years" [class.selectedYear]="year === selectedYear"
       [class.currentYear]="year === date.getFullYear()" (click)="onYearClick(year)">{{ year }} 
  </div>

I'm really not sure if this is at all possible though. Inside my onYearClick() method, I am referencing the DOM elements, which have classes selectedYear or currentYear. The console.log of these DOM elements returns undefined, however:

  @ViewChild('currentYear') currentYearDOM?: ElementRef;
  @ViewChild('selectedYear') selectedYearDOM?: ElementRef;

  onYearClick() {
    console.log(this.date.getFullYear());
    console.log(this.currentYearDOM);
    console.log(this.selectedYearDOM);

So, I have two questions:

  1. Is it possible to toggle more than one CSS class using the above mentioned template notation?
  2. Why are these objects undefined? The DOM elements with the respective classes exist

=============================================

Update: I have tried using the following statement in my div instead:

[ngClass]="{'selectedYear': year === selectedYear,'currentYear': year === date.getFullYear() }"

, but the problem remains.

I really think there is sth wrong with the way I toggle these classes:

When I first open the view, the right div, which contains the current year, is marked with the currentYear CSS class. Then, when I click on another year, close the view and open it again, the selected year is marked with the selectedYear CSS class, but the current year has lost its currentYear CSS class. Why would this happen?

Also: the console.log of my ViewChild components always prints undefined. So, I assume there is something wrong with the way I am trying to reference my DOM elements.

=======================================================

another update:

I found the issue: The condition for currentYear was just wrong. Wow, that's a bit stupid. Sorry!

CodePudding user response:

Try this:

<div [ngClass]="{'class1': yourCondition1, 'class2': yourCondition2}"></div>
  • Related