Twitter LogoFacebook Logo
Attribute Directives in Angular
Attribute Directives in Angular
By: King

Attribute directives are add-ons that we can add to the HTML DOM elements, in-line, inside the HTML page. We can use them to add additional features and behaviors to the element. 

There are many of them already available in Angular. But we will create our own.

Open your Angular project on VS code.  To begin, create an attribute directive call CustomAttribute by using the ng generate directive command.

ng generate directive CustomAttribute

This command will create a directive TypeScript file and add it to our app module so it can be used in the application. 

...
import { CustomDirectiveDirective } from './custom-directive.directive';

@NgModule({
  declarations: [
    ...
    CustomDirectiveDirective
  ],
  imports: [
    ...
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { 
  constructor(){

  }
}

Inside the directive TypeScript file, there is a @Directive decorator on top of our class declaration to indicate that this class is a directive.

import { Directive } from '@angular/core';

@Directive({
  selector: '[appCustomDirective]'
})
export class CustomDirectiveDirective {

  constructor() { }

}

The selector property is the name we use to add the directive to an element.

Go to the app component html page. Add a paragraph element and give it some text. 

Add the custom attribute directive to the paragraph. Get the value from the selector property in the directive decorator and then place it inside the open tag of the element.

<appCustomDirective>This is a very long text.</p>

Save the project and start the local server. Open the browser and go to localhost:4200.

Image from Codeible.com

As you can see, our application still works, but nothing is happening. That is because we have not defined anything in the class file.

Go back to VS code. Go to the custom attribute directive TypeScript file.

Let’s say that this attribute will change the text color of elements to red. 

Normally to do this, we would get a reference of the element with the getElementById() function, access the style property, and then set the color.

getElementById().style.color = "red";

But in Angular, it will automatically pass in the reference of the element that is using this attribute through the constructor. So, we can declare a parameter in the constructor to take in the reference as an argument. Then we can declare a variable to store the reference and use it in our code.

private htmlElement: HTMLElement;

constructor(element: ElementRef) {
   this.htmlElement = element;
}

To change the color of the text, we take the reference, access the style property, and then set the color to red.

this.htmlElement.style.color = "red"

So now, it will turn our text to red. Let’s verify that. Save the project and go to the browser.

Image from Codeible.com

As you can see it turned the color of the text to red.

We can also use attribute directives to add DOM events to the element. Go back to VS Code. 

Go to the custom directive typescript file. Let’s say that we want to change the color of our text to orange when we click on the element. 

Normally, we would take the reference of the element and call the addEventListener function to add an event. 

 this.htmlElement.addEventListener();

But there is a more proper way to add events in attribute directives. 

We should use the host listener decorators. These decorators let us listen to the DOM events of the host. 

If you are curious to who the host is, the host is the element that is using the attribute. So if we put this in a paragraph element, that paragraph element is the host. Similarly, if we put this in a component, that component will be the host.

Let’s see how we can listen to a click event using the host listener decorator.

To begin, add HostListener to the import. This will allow us to use the host listener decorator. 

import { Component, HostListener } from '@angular/core';

Define a method that you want to use for an event. Add the @HostListener decorator as part of the method declaration to start listening to an event. 

Inside the parenthesis, we put the event we want to listen to. Lastly, In the body of the method, put the code to change the color of the text to orange. 

@HostListener("click")

onClick(){
   this.htmlElement.style.color = "orange"
}

Now elements that has this attribute will listen for any click events and change the text color to orange.


Save the project and go to the browser.

In addition to events, we can also add inputs and outputs to insert and broadcast information.

Go back to VS Code. 

Instead of using static values like orange, we may want to be able to use any color. Therefore, we would declare an input.

Add input to our import so we can start declaring inputs.

import ComponentHostListener, Input from '@angular/core';

Then declare an input variable and instead of using orange, we will use the value of the input.

@Input() color: string;

@HostListener("click")

onClick(){
   this.htmlElement.style.color = this.color;
}

Go to the app component html page. 

To access inputs of an attribute directive, we use the square bracket syntax and then provide the name of the input we want inside the brackets. Then we assign a value that we want to insert. We will use purple.

<appCustomDirective [color]="purple">This is a very long text.</p>

So right now, the color of our text should change to purple instead of orange when we click on it. 

Save the project and go to the browser. 

I want to mention one more thing, go back to VS Code.

Right now, we have an attribute directive and an input from the attribute separately from each other in the element. We can combine the two like this:

<p [appCustomDirective]="purple">This is a very long text.</p>

This is called the compact syntax.


To do this is simple, we need to change the name of our input to match the value of the selector property for the attribute directive. Since the value of the selector property is appCustomAttribute, change the input name to appCustomAttribute.

@Input() appCustomAttributestring;

Save the project and go to the browser.

Recap

Let’s take a moment to recap what we have learned.

1. We learned how to create an attribute directive using the ng generate directive command.

2. We learned that attribute directives are add-ons that we can add to HTML DOM elements, in-line, in the HTML page and that they are used to add additional features and behaviors to the elements that it is added to.

3. We learned how to add the attribute to an element, by taking the value of the selector property in the directive decorator and placing it in the opening tag of the element.

4. We learned that Angular passes a reference of the element that we apply  the attribute directive to in the constructor.

5. We learned how to add events by using HostListeners

6. We also learned how to use the compact syntax to add the attribute to the element and insert a value at the same time.


Sign In