How to useAttribute Directives in Angular

Create a new directive using the following command

ng generate directive attribute-directive

Folders Structure:

Attribute Directive Structure

Code Example:

HTML
<!-- app.component.html -->

<div appAttributeDirective [colorName]="'yellow'" [opacity]=0.4>
    Hover over me to see the magic!
 </div>
 
JavaScript
//attribute-directive.directive.ts

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

@Directive({
    selector: '[appAttributeDirective]'
})
export class AttributeDirectiveDirective {

    constructor(private elementRef: ElementRef) { }

    @Input() colorName!: string;
    @Input() opacity!: number;

    @HostListener('mouseenter') onMouseEnter() {
        this.highlight(this.colorName, this.opacity);
    }

    @HostListener('mouseleave') onMouseLeave() {
        this.highlight('', 1);
    }

    private highlight(color: string, opacity: number) {
        this.elementRef.nativeElement.style.opacity = opacity;
        this.elementRef.nativeElement.style.backgroundColor = color;
    }

}

Output:

Browser


How to pass multiple parameter to @Directives in Angular ?

Angular directives are TypeScript classes decorated with the @Directive decorator. These are powerful tools for manipulating the DOM and adding behavior to elements. They can modify the behavior or appearance of DOM elements within an Angular application.

Directives can be broadly categorized into three types:

  1. Component Directives: These are directives with a template and can be used as standalone components.
  2. Attribute Directives: These change the appearance or behavior of an element, component, or another directive.
  3. Structural Directives: These change the DOM layout by adding or removing elements.

We will discuss the following approaches to pass multiple parameter to @directives in Angular:

Table of Content

  • Using Component Directives
  • Using Attribute Directives
  • Using Structural Directives

Similar Reads

Steps to Create Angular Project

Step 1: Create a new Angular project using the following command....

Approach 1: Using Component Directives

Create a new component suing the following command....

Approach 2: Using Attribute Directives

Create a new directive using the following command...

Approach 3: Using Structural Directives

Create a new directive using the following coammand....