08 Structural Directives 2/2

Maurício Alexandre Barroso
3 min readJul 17, 2021

In the previous article we talked about structural directives and gave two examples of the two most used in Angulas projects: NgIf and NgForOf. However, there are other ready-to-use directives as useful as the two mentioned above. Let's see a little about two more directives and it will be a challenge for you to implement the others existing in your project. Are you ready?! =D

NgClass

The NgClass directive serves to add classes to an html tag based on some conditional. There are some syntaxes for its implementation, in our example we will see one of them.

Let's take advantage of the design we've been using in this series of articles. Below is the code needed to see the NgClass directive in action.

.html file of our component
.ts file of our component
.scss file of our component

In terminal, run the ng serve command and see the result in your browser.

We've added the NgClass directive to the h2 tag that prints our username. The ‘blue-color’ class that we pass inside the object to the directive will be added whenever the variable this.blueColor is true. A simple example that already exemplifies a way to add styles based on a conditional.

NgStyle

The NgStyle directive allows us to add an inline styling to a specific tag. We can pass an object, following a specific model, and add a style directly to the tag. This practice has benefits but should be used very sparingly, as adding styling to a tag directly, not through a .scss file, is not a good practice as it can overload your project, causing it to load slowly, for example . Use NgStyle sparingly! :)

Just like the previous example, let's implement the logic needed to see this directive in action in our project!

.html file of our component
.ts file of our component

Run the ng serve command in your terminal and see the result in your browser.

When we click on the ‘Add Styles object’ button, we assign the this.objStyles object the ‘color: ‘#468120’’ propriedade property. In the h2 tag that prints our user's age information, the [ngStyle] directive takes this object and adds inline styling to the tag. Fantastic, isn't it!? =D

Once again we can see the power of directives within Angular projects. It's very important to practice, create new conditionals, and test the code we've done in this article so that the concepts are clear to you. Knowledge comes with practice, remember that. Good studies! =D

--

--