skip to content
Alvin Lucillo

Attribute directive for standalone component

/ 1 min read

💻 Tech

Attribute directive allows you to modify the appearance and behavior of a component by simply applying it as an attribute. By doing so, the component will gain the behavior defineed by the directive.

Example of applying a directive to a component:

<!-- app.component.html -->
<div>
  <p appHighlight>Hello</p>
</div>

First, generate a directive: ng generate directive highlight

Modify the generated file highlight.directive.ts to define how it will change the behavior and appearance of the component. This directive simply changes the background color of a component’s element.

// highlight.directive.ts
import { Directive, ElementRef, Renderer2, HostListener } from '@angular/core';

@Directive({
  selector: '[appHighlight]',
  standalone: true,   // required for standalone component
})
export class HighlightDirective {
  constructor(private el: ElementRef, private renderer: Renderer2) {}

  @HostListener('mouseenter') onMouseEnter() {
    this.highlight('yellow');
  }

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

  private highlight(color: string) {
    this.renderer.setStyle(this.el.nativeElement, 'backgroundColor', color);
  }
}

Import the directive into the component that will use it.

// app.component.ts
import { Component } from '@angular/core';
import { RouterOutlet } from '@angular/router';
import { HighlightDirective } from './highlight.directive'; // imports the directive


@Component({
  selector: 'app-root',
  standalone: true,  // required for standalone component
  imports: [RouterOutlet, HighlightDirective],
  templateUrl: './app.component.html',
  styleUrl: './app.component.css',
})
export class AppComponent {}