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">
Plunker
So far we've looked at adding just single classes, which is something the NgClass directive can also help us with as it supports multiple classes. Using multiple classes is the real reason to use the NgClass directive. You can think of NgClass as being able to specify multiple [class.
Angular class binding can also be done to multiple classes by using a generic [class] binding without the dot (for example, [class]="classExpr"). You can format it as an object (object, Array, Map, Set, etc) with class names as the keys and truthy/falsy expressions as the values.
yes , you can do it. Did you try it? What happened? You can use both class and ngClass as the first one gives you the opportunity to apply a class that you want to implement in all cases under any circumstances and the later to apply classes conditionally.
ngClass is more powerful. It allows you to bind a string of classes, an array of strings, or an object like in your example. The above two lines of code is with respect to CSS class binding in Angular. There are basically 2-3 ways you can bind css class to angular components.
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
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">
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With