Introduction to Attribute Directives

Let’s learn about the foundations of attribute directives and how they work.

This chapter is entirely about attribute directives in Angular and the basic concepts surrounding them. In this lesson, we’ll cover these two things:

  • Pass data
  • Handle events

Finally, we’ll create our own attribute directive. Let’s go!

Attribute directives

Let’s review the three types of directives in Angular, which are as follows:

  • Components
  • Attribute directives
  • Structural directives

Attribute directives can change the appearance or behavior of any existing element. So, we can use them on standard HTML elements in templates and other components, or even trigger other directives! They’re very flexible because of the possibilities given by the directive’s selector.

Right now, let’s start with examples of elementary directives to smoothly introduce the concept of attribute directives. We’ll cover very interesting use cases later on that can help implement larger projects, and avoid unnecessary duplications or unclear architecture.

In this lesson, we’ll use an example of a directive that can be used on images to set their size to an application’s standard avatar size, which is 64 x 64 px.

Build an attribute directive

To generate a directive file, we can use the Angular CLI command. Or, we can make a file of our own and write the code from scratch. Let’s use the recommended option of using the Angular CLI command. First, however, let’s see how it’s done step by step so that we can follow the same steps to make our own file.

Get hands-on with 1200+ tech skills courses.