Angular - 2.25-Dynamically apply CSS classes with ngClass

We have seen examples for Ng style and NGIF. Now one thing related to Ngstyle is the NG class. We have now learned that NG style allows us to dynamically assign a style. Similarly, the class allows us to dynamically add or remove CSS classes.

To create such a class, we will add our styles and use the back text to write this on multiple lines. We will give this class the name "online" in this case, because we want to color the text white. This is all we want to do because it is difficult to read the black text on the green background.

The "ng class" directive also works only as intended when using the property link. It should also be bracketed. For this directive property, we must also pass a JavaScript object. Each property we link may have a different value, such as "disabled" that takes true or false.

For the "ng class" object, we have key-value pairs. Keys are the names of CSS classes and values are the conditions that determine whether or not this class should be attached. So here we have the "online" class. You can also put it in single quotes if you had a class name with a dash inside or something like that.

We want to attach this only if the server is online, so only if the "serverStatus" is online equal to "online", which is a string in single quotes. Of course, we can also outsource this in a method called "this serverStatus equal to online verification", but here, we will write it online.

If it is online, we must attach the "online" CSS class to this paragraph. Otherwise, it must not be attached. Let’s look at this in the current application. Both are offline, so neither should have the "online" CSS class added. Indeed, I can’t find the class on either.

Let’s reload and hope one is offline or online. Both are, so let’s check them. Now we see that the "online" class has been added. In fact, it was added for both because that’s how the "ng class" directive works.

This is an example of an integrated directive and an integrated attribute directive.