angularng-class

ngClass not applying css classes initially, only after click


I am trying to dynamically add css classes to a button in angular 9. I am conditionally adding one class or another based on a boolean value. I also have a click event that toggles the same boolean value. The issue I'm having is that when the page loads, neither css class is applied. Only after clicking the button is one class or the other applied, and after that, the css classes toggle as expected. I've searched SO for similar issues, but couldn't find any that were similar enough to my problem to help me find a solution. I've also googled and read several times how to use ngClass. As it seems like what I'm trying to do should be very straightforward, I'm guessing I'm missing something obvious. Here are the code snippets:

delivery-schedule.component.html:

<div>
    <app-date-button></app-date-button>
</div>

date-button.component.html

<button 
    class="btn-date" 
    (click)="toggleSelected()"
    [ngClass]="[isSelected ? 'selected' : 'unselected']">
    <div class="day">Fri</div>
    <div>Jan 1</div>
</button>

date-button.component.ts

import { Component, OnInit, Input } from '@angular/core';

@Component({
  selector: 'app-date-button',
  templateUrl: './date-button.component.html',
  styleUrls: ['./date-button.component.sass']
})
export class DateButtonComponent implements OnInit {

  constructor() { }

  isSelected: boolean = false;

  toggleSelected() {
    this.isSelected = !this.isSelected;
  }

  ngOnInit() {
  }
}

When my app loads, I get class="btn-date", but after clicking the button, I get class="btn-date selected".

I'm hoping to get class="btn-date unselected" initially. Any guidance would be much appreciated. Thanks!


Solution

  • Edit:

    Since the StackBlitz provided by @cjd82187 works fine with your code, there might be some error elsewhere in your code (e.g. check the developer console of your browser).

    Old answer:

    Try to change your ngOnInit to:

    isSelected: boolean;
    
    ...
    
    ngOnInit() {
      this.isSelected = false;
    }
    

    Or to implement AfterViewInit:

    A lifecycle hook that is called after Angular has fully initialized a component's view.

    export class DateButtonComponent implements OnInit, AfterViewInit {
    
      isSelected: boolean;
    
      ...
    
      ngAfterViewInit() {
        this.isSelected = false;
      }
    }