Write Your Own Attribute Directive

Let’s implement custom attribute directives.

In this lesson, we implement a few attribute directives that could be very useful in the event of an Angular challenge! The examples we use are real application cases and describe common patterns for creating custom directives. So, let’s get started!

Common image attributes

An image’s HTML element comes with a set of attributes that add additional information or behaviors for <img> elements. However, when very similar patterns are applied across the application, they make the duplicate the code and make it harder to change.

Let’s consider an online store application. It’s clear that the number of images on pages like this will be huge, and they’ll work very similarly.

Let’s imagine that the product in the store is defined with an interface like this:

interface Product {
	id: string;
	name: string;
	price: number;
	image: string;
	description: string;
}

Each time the product image is added in the template, it changes like this:

<img [src]="product.image">

It might also look like this:

<ng-container *ngFor="let item of products">
	<img [src]="item.image">
</ng-container>

Let’s consider that images should have at least an alt attribute. This means each time the image is used, it needs to be implemented as seen below:

<img [src]="product.image" alt="Image shows {{product.name}}">

There could be dozens of elements like this in the application code!

Another intersting feature of these images is their lazy loading, which is great in the context of our application. It can be added like this:

<img [src]="product.image" 
		  alt="Image shows {{product.name}}"
      loading="lazy">

So, each time we add a new image, we have to remember these three common items (alt, <img>, and lazy) and set them correctly, increasing the duplications.

Let’s imagine a feature to implement a title attribute in all images across the application. It is a nightmare with such a complicated codebase! Creating a custom directive that wraps those attributes in a single call is a great way to refactor this application code, which is what we’ll do now.

After we’re done refactoring, we can apply the directive to existing images in the application and check to see if it works.

Let’s remember what we learned so far which might be useful during this task. We know how to:

  • Declare the appropriate selectors for directives.

  • Change the directive’s host element.

  • Pass data to a directive.

Get hands-on with 1200+ tech skills courses.