One of the common requirements in Angular applications is to apply classes conditionally based on certain conditions. The ngClass directive provides a convenient way to achieve this.
You may encounter an error like "Cannot read property 'remove' of undefined" when using ngClass in a particular way. This error indicates an incorrect usage of the directive.
Angular 2 and above offers several options for applying conditional classes:
Option 1:
[class.my_class] = "step === 'step1'"
This syntax adds the 'my_class' class only if the 'step' variable equals 'step1'.
Option 2:
[ngClass] = "{'my_class': step === 'step1'}"
This option uses an object literal to specify the condition and the corresponding class to be applied.
Option 3:
[ngClass] = "{'1' : 'my_class1', '2' : 'my_class2', '3' : 'my_class4'}[step]"
This method utilizes a hash lookup to apply the appropriate class based on the value of the 'step' variable.
Option 4:
[ngClass] = "step == 'step1' ? 'my_class1' : 'my_class2'"
This syntax uses the ternary operator to conditionally set the class based on the 'step' variable.
In your code, you stated using ngClass={active: step==='step1'}, which is not the correct syntax. Instead, use one of the options outlined above. For example:
<ol> <li [ngClass]="{'active': step==='step1'}" (click)="step='step1'">Step1</li> <li [ngClass]="{'active': step==='step2'}" (click)="step='step2'">Step2</li> <li [ngClass]="{'active': step==='step3'}" (click)="step='step3'">Step3</li> </ol>
Adopting one of these alternative approaches should resolve the error you were encountering. Refer to the Angular documentation for further details.
The above is the detailed content of How to Correctly Use `ngClass` for Conditional Styling in Angular?. For more information, please follow other related articles on the PHP Chinese website!