Reputation: 352
I'm trying to add variable-driven class(es) to an element, along with other classes using ngClass.
Example:
// inputExtraClass = 'form-control-sm'
// Working
<input class='form-control' [ngClass]="inputExtraClass" placeholder="Working">
// Not working
<input class='form-control' [ngClass]="{inputExtraClass: true}" placeholder="Not working">
Upvotes: 9
Views: 14360
Reputation: 506
If someone wants to directly use the class name with the dynamic variables, without any conditions, then they can use this way.
<div class="card-table second" ngClass="{{source}} {{currentMode}}">
Upvotes: 0
Reputation: 1241
You can use the "array form" (https://angular.io/api/common/NgClass#description) in this way:
cond1 = true;
cond2 = false;
smClass = 'form-control-sm';
xlClass = 'form-control-xl';
<input class='form-control' [ngClass]="[ smClass, cond1 ? 'form-control-lg' : '', cond2 ? xlClass : '' ]">
This will be:
<input class="form-control form-control-sm form-control-lg">
Upvotes: 5
Reputation: 988
Providing a kind of complete answer to your question,
Do: <input class='form-control' [ngClass]="{'inputExtraClass': true}" placeholder="Not working">
and if you want more than one class or switch between classes you can also do something like
<input class='form-control' [ngClass]="{'inputExtraClass': true, 'notInputExtraClass': !true }" placeholder="Not working">
this way above, it will be either one class or the other
You can also aply any other variation you like using this, or make a property in your component like this one:
toggleClass: boolean = true;
and in your html:
<input class='form-control' [ngClass]="{ 'inputExtraClass': toggleClass, 'notInputExtraClass': !toggleClass }" placeholder="Not working">
same idea, and then you could create a method and change the toggleClass property or whatever :) hope it helped
Upvotes: 12
Reputation: 183
You can use expressions inside ngClass:
<input class='form-control' [ngClass]="(addClassIfTrue) ? 'inputExtraClass' : ''" placeholder="Working">
Upvotes: 0