Attribute directives: Built in - lordoftheflies/angular-essential-training GitHub Wiki

Attribute directives are designed to change the appearance or behavior of the DOM elements that they are attached to. They do not create or remove DOM elements like structural directives. Let's take a look at how you can use a built-in attribute directive. In the media dash item dash list dot component dot html file, we will make use of the ngClass attribute directive to get some CSS classes onto the mediaItem elements based on the mediaItem medium type. Now the project already has CSS rules set up in the media-item.component.css file for some classes. So we can just start using those in the template. So on the mw-media-item element, we use the directive property template syntax using the square brackets around the term ngClass, and set that equal to a statement. The ngClass directive expects an object structure for its statement value with the CSS classes for the property names and a true false for the values. In our case, we want to have two CSS classes, one named medium-movies and one named medium-series. Since the dash is not valid in an object property, we need to use single quotes around the term. We want to check the mediaItem.medium property to see if is movies or series for each of these CSS classes, and if true, then use it. We can do that with a statement that evaluates the true or false for each of these. So we set the value of medium-movies to mediaItem.medium, triple equals, and then Movies in single quotes. And we set the value of medium-series to mediaItem.medium, triple equals Series in single quotes. And if we switch over to the browser, we see different colors for the media items. And if we inspect the DOM, we can see that the media items are getting the appropriate class applied to them from the ngClass attribute directive.