1

I am a novice to Angular and was learning about class binding through a tutorial, that was explaining the concept in Angular 6.

I now have basic clarity on how we use ngClass directive to bind multiple CSS classes in different ways (i.e., by using key-value object, string, or an array). However, I noticed that I was able to get the same result if I used [class] instead of [ngClass] as shown in the code snippet below. I am using Angular11 in my system to practice the concepts.

@Component({
  selector: '[app-test]',
  template: `
    <h2 [class]="{'text-success': !hasError, 'text-danger': hasError, 'text-special': isSpecial}">Multi-class binding</h2>
    <h2 [ngClass]="{'text-success': !hasError, 'text-danger': hasError, 'text-special': isSpecial}">Multi-class binding</h2>
  `,
  styles: [`
        .text-success{
          color: green;
        }
        .text-danger{
          color: red;
        }
        .text-special{
          font-style: italic;
        }
  `]
})
export class TestComponent implements OnInit {
  hasError = true;
  isSpecial = true;
}

I went through other similar questions here, but they seem to be answering the questions based on older versions (ex: Difference between [ngClass] vs [class] binding).

So, I am curious to know if ngClass solves any other issue or provides any additional advantage apart from multi-class binding (that we can achieve with [class] binding only). Or, is the ngClass use now redundant in Angular 11?

0 Answers0