NgClass

Similar to ngStyle, ngClass allows us to define and toggle class names programmatically in a DOM element using a convenient declarative syntax. This syntax has its own intricacies, however. Let's see each one of the three case scenarios available for this example:

<p [ngClass]="{{myClassNames}}">Hello Angular!</p>

For instance, we can use a string type so that if myClassNames contains a string with one or several classes delimited by a space, all of them will be bound to the paragraph.

We can use an array as well so that each element will be added.

Last but not least, we can use an object in which each key corresponds to a CSS class name referred to by a Boolean value. Each key name marked as true will become an active class. Otherwise, it will be removed. This is usually the preferred way of handling class names.

There is an alternate syntax to ngClass, which is in the following format:

[ngClass]="{ 'class' : boolean-condition, 'class2' : boolean-condition-two }"

In short it is a comma separated version where it will apply a class when a condition is true. More than one class can be applied if more than one condition is true. It would look something like this if used in a more realistic scenario:

<span [ngClass] ="{
'light' : jedi.side === 'Light',
'dark' : jedi.side === 'Dark'
}">
{{ jedi.name }}
</span>

The resulting markup could be the following if jedi.side has the value light then add CSS class light to the span element:

<span class="light">Luke</span>
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset