06 Angular Attribute Directives

Maurício Alexandre Barroso
3 min readJul 4, 2021

We are going deeper and deeper into the basics of Angular. In this step we will talk about structural directives and attribute directives. Have you ever heard of these terms? Let's know it in a simple way and with an example of use for each of them and I bet that by the end of this article you will know exactly what each one means. :)

Attribute Directives

Directives are how we assign a behavior to a particular element of the DOM. Its use is through a marker on the element that we want to assign a certain behavior.

In our example we will create our directive and we will do something very simple with it: we will change the color of our text.

First step is to create our directive using the command below:

The above command will create our directive named blue-directive. To make our project more organized, note that in yellow I defined the name for a folder that will be created and that will contain our directive. It's a way to keep our project organized.

A very important detail that we must always be aware of is that in order to access the features of our directive, we have to declare it in the module of the component that will use it. By default Angular will add the module from our directive in the app component.

Now let's open our blue.directive.ts file. Note that, like a component, the directive has a Decorator that indicates its functionality and a selector. In order to test and understand how to use a directive, let's use the concept of Dependency Injection. Add the following code to the constructor:

Now in our first-component.component.html file, in the h1 tag referring to name, add the directive selector. In our case, appBlue.

See the result:

The color defined in our directive was applied to the element that received the identifier selector of the directive we created! Supimpa, no!? You already know how to use Angular attribute directives. =D

In the next article we will look at two extremely important structural directives used in Angular designs. Review the content seen so far, make tests and code changes to fix the concepts. Knowledge comes with practice, so good studies!

--

--