0

I ran into a strange Angular behavior... I don't know if it ever happened to any of you.

Binding variable applying the traditional binding by using the double curly brace syntax is not going to work as expected, it will replace previous classes already associated instead of appending.

Did you know how to concatenate classes instead of replacing existing ones?

As you can see from this example, here it replaces the classes associated with mat-raised-button of material.

Simple test case :

html

<button mat-raised-button class="myClass">BUTTON</button>
<button mat-raised-button class="{{test}}">BUTTON</button>

.ts

export class AppComponent {
   ...
   test = 'myClass';
   ...
}

css

.myClass {
  background: red;
}

Stackblitz test case

Fmerco
  • 1,160
  • 5
  • 20

2 Answers2

2

Yes, try using ngClass directive from Angular to append.

https://alligator.io/angular/class-binding-ngclass-angular/

AliF50
  • 16,947
  • 1
  • 21
  • 37
  • Fast and easy. Thanks – Fmerco Mar 02 '20 at 14:36
  • I wonder if this will solve your problem, you want to add a variable string as a class to the element, I am thinking.... – AliF50 Mar 02 '20 at 14:36
  • If you want to append to a class you already have, you can try out this answer: https://stackoverflow.com/questions/49026960/concat-classname-with-variable-angular-2 – AliF50 Mar 02 '20 at 14:39
2

Use ngClass directive to append your classes based on conditions.

<button mat-raised-button ngClass="{{test}}">BUTTON</button>
Shravan
  • 1,182
  • 8
  • 21