Attribute Directive

Baskarasothy Pratheeparaj
2 min readSep 13, 2020

Attribute Directives are used to change the behavior, appearance or look of an element on a user input or via data from the service. Essentially, there are three types of directives in Angular

Type of Directives

In this post, we will learn how to create Attribute Directives in Angular. So let’s say we want to change the background color of an element; in that case we would apply the attribute directive to the element.

Create first Attribute directive

Let’s start with creating the Attribute Directive. To do this, we need to create a class and decorate it with @directive decorators. A simple attribute directive to change the color of an element can be created as shown in the next listing

import { Directive, ElementRef, Renderer } from '@angular/core';

@Directive({
selector: '[chcolor]'
})
export class ChangeColorDirective {

constructor(private el: ElementRef, private render: Renderer) {
this.changecolor('red');
}

private changecolor(color: string) {

this.render.setElementStyle(this.el.nativeElement, 'color', color);
}
}

While we are creating an attribute directive to change the color of the element, keep in mind that we don’t need to create a new attribute directive to just change the color . simple colors can be changed by using property binding. However, the attribute directive we created will change color of an element in this example.

User Input in attribute directive

We may have a requirement to apply an attribute directive on the basis of some user inputs to change the color of the element when the user mouses over or mouse hovers on the element.we need to decorate methods with the @HostListener decorator. To do this, we need

1.capture user input or action, and

  1. apply a color or clear color respectively.
import { Directive, ElementRef, Renderer, HostListener, Input } from '@angular/core';

@Directive({
selector: '[chcolor]'
})
export class ChangeColorDirective {
constructor(private el: ElementRef, private render: Renderer) { }

@HostListener('mouseenter') methodToHandleMouseEnterAction() {
this.changecolor('red');
}
@HostListener('mouseleave') methodToHandleMouseExitAction() {
this.changecolor('blue');
}
private changecolor(color: string) {

this.render.setElementStyle(this.el.nativeElement, 'color', color);
}
}

As you can probably tell, we have added two methods to handle user actions. On mouse enter and mouse leave, we are changing the color to red and blue respectively.

Conclusion

In this post we learned about Attribute Directives in Angular , and created them to change the behavior or appearance of an element, i hope its will be a helpful things . thanks for Reading !!!

--

--