Write Your Own Attribute Directive
Let’s implement custom attribute directives.
We'll cover the following...
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 ...