How to use NgClass in angular?

NgClass 


    The NgClass directive allows you to set the CSS class dynamically for a DOM element.

    There are two ways to use this directive, the first is by passing an object literal to the             directive.  

  
    You can use NgClass using below syntax
        
                [ngClass]="{'text-success':true}"


     When using an object literal, the keys are the classes which are added to the element if the value of the key evaluates to true.

So in the above example, since the value is true this will set the class text-success onto the element the directive is attached to.

The value can also be an expression, so we can re-write the above to be.


[ngClass]="{'text-success':person.country === 'UK'}"    


Let’s implement the colored names demo app using ngClass


<h4>NgClass</h4>

<ul *ngFor="let person of people">

  <li [ngClass]="{

    'text-success':person.country === 'UK',

    'text-primary':person.country === 'USA',

    'text-danger':person.country === 'HK'

  }">{{ person.name }} ({{ person.country }})

  </li>

</ul>


Since the object literal can contain many keys we can also set many class names.

We can now color our text with different colors for each country with one statement.

If we run the above code we would see:



 Alternative Syntax


We can also set a class on an element by binding to the input property binding called class, like so [class]="'text-success'"


If we want to just add text-success to the list of classes already set on the element we can use the extended syntax [class.<class-name>]='truthy expression'

So for instance to add text-success to the list of classes for an element we can use:

[class.text-success]="true"

Or just like before we can use an expression as the value, like so:

[class.card-success]="person.country === 'UK'"

And we can actually specify multiple values at one time, like so:



<ul *ngFor="let person of people">

  <li [class.text-success]="person.country === 'UK'"

      [class.text-primary]="person.country === 'USA'"

      [class.text-danger]="person.country === 'HK'">{{ person.name }} ({{ person.country }})

  </li>

</ul>




Comments

Popular posts from this blog

Angular Best Practices and Coding Standards: A Guide for Developers

How to SSH AWS EC2 instance?

Top 7 ways to use Interceptors in Angular