Attribute Directive in Angular

quiz
Challenge Inside! : Find out where you stand! Try quiz, solve problems & win rewards!

Overview

Directives are classes that provide extra functionality to components in your Angular applications. To control forms, lists, styles, and what users view, utilise Angular's built-in directives.

The attribute directive modifies the look or behaviour of a DOM element. These directives appear in templates as standard HTML attributes.

Scope

This article will go through angular attribute directives. What we can accomplish with attribute directives, different types of built-in directives, and how to develop custom directives.

Introduction to Attribute Directives

Angular attribute directives are wrapped by brackets, indicating to Angular that the appearance or behavior of the DOM elements included within the directive may vary based on specific situations.

When Do We Use Attribute Directives?

When you want logic or events to affect the appearance or behaviour of a view, you'd use an attribute directive.

When you have a UI element that will be used across your project, you can use an attribute directive to share it between components and modules to avoid writing the same code twice.

Most Commonly Used Attribute Directives

There are a few angular attribute directives that are often used:

  • ngClass
  • ngStyle
  • ngModel

Usage of ngClass

Data bindings may be used to control an element's class memberships in three ways: regular property binding, special class binding, and the ngClass directive. Each of the three is discussed below, and each functions somewhat differently and is beneficial in different situations.

Example

<div [class]="expr"></div>

This binding analyses the expression and replaces any existing class with the result.

Example

<div [class.myClass]="expr"></div>

This binding evaluates the expression and uses the result to determine whether or not the element belongs to myClass.

Example

<div [ngClass]="map"></div>

This binding uses the data in a map object to set the class membership of several classes.

Usage of ngStyle

Data bindings may be used to set the style properties of the host element in three ways: ordinary property binding, special style binding, and the ngStyle directive.

Example

<div [style.myStyle]="expr"></div>

This is the standard property binding, which is used to assign a single style property to the expression's outcome.

Example

<div [style.myStyle.units]="expr"></div>

This is a particular style binding that allows you to provide the units for the style value as part of the target.

Example

<div [ngStyle]="map"></div>

Using the data in a map object, this binding sets numerous style attributes.

Usage of ngModel

The ngModel directive is used to bind the values of HTML controls (input, select, and textarea) or any custom form controls, and it keeps the needed user value in a variable that we can use anytime we need that value. It is also used in form validation.

Example

<input [(ngModel)]="name" #ctrl="ngModel">

Building Custom Attribute Directives and Applying Them

Let's begin by making the Attribute Directive. To do this, we must first construct a class and then decorate it using @directive decorators.

highlight.directive.ts

@Directive({
    selector: '[highlight]'
})
export class HighlightDirective {
 
    constructor(private el: ElementRef, private render: Renderer) {
        this.highlightColor('yellow');
    }
 
    private highlightColor(color: string) { 
        this.render.setElementStyle(this.el.nativeElement, 'color', color);
    }
}

Now, add HighlightDirective in AppModule

app.module.ts

import { HighlightDirective } from './highlight.directive';
 
@NgModule({
    imports: [BrowserModule, FormsModule, HttpModule],
    declarations: [AppComponent, HighlightDirective],
    ...
})
export class AppModule { }

Let's use highlight attribute in app.component.ts template as follows

app.component.ts

@Component(
    {
        selector: 'app-container',
        template: `<h1 highlight>{{title}}</h1>`
    })
export class AppComponent {
    title: string = "This is heading";
}

Handling User Events

We may need to apply an attribute directive based on certain user inputs to alter the colour of the element when the user mouses over or hovers the mouse over the element.

We can call multiple methods to handle different user actions based on the user activities. Methods must be decorated with the @HostListener decorator to handle user actions such as mouse enter.

As seen in the following example, we may edit directives to handle user input.

import { Directive, ElementRef, Renderer, HostListener, Input } from '@angular/core';
 
@Directive({
    selector: '[highlight]'
})
export class HighlightDirective {
    constructor(private el: ElementRef, private render: Renderer) { }
 
    @HostListener('mouseenter') methodToHandleMouseEnterAction() {
        this.highlightColor('yellow');
    }
    
    @HostListener('mouseleave') methodToHandleMouseExitAction() {
        this.highlightColor('blue');
    }
    
    private highlightColor(color: string) { 
        this.render.setElementStyle(this.el.nativeElement, 'color', color);
    }
}

Passing Values into an Attribute Directive

Let us use binding to send data to the directive in the next part. We will use the @Input() decorator and add a property to the directive class to link the directive with data:

@Input('highlight') highlightColor: string;

Let's use it in the directive

import { Directive, ElementRef, Renderer, HostListener, Input } from '@angular/core';
 
@Directive({
    selector: '[highlight]'
})
export class HighlightDirective {
    
    @Input('highlight') highlightColor: string = 'yellow';
    constructor(private el: ElementRef, private render: Renderer) { }
 
    @HostListener('mouseenter') methodToHandleMouseEnterAction() {
        this.highlightColor(this.highlightColor);
    }
    
    @HostListener('mouseleave') methodToHandleMouseExitAction() {
        this.highlightColor();
    }
    
    private highlightColor(color: string = null) { 
        this.render.setElementStyle(this.el.nativeElement, 'color', color);
    }
}

Setting Value with User Input

We may specify a value for the highlight property, and it will manage the highlighter colour.

app.component.html

<div>
    <h1 highlight='blue'>{{title}}</h1>
    <p highlight='red'>{{ message1 }}</p>
    <p highlight>{{ message2 }}</p>
</div>

Conclusion

  • Attribute Directives are used to modify the behaviour, appearance, or appearance of an element based on user input or data from a service
  • There are few built-in directives available
    • ngClass
    • ngStyle
    • ngModel
  • Custom directives can be created according to users requirement
Free Courses by top Scaler instructors