Back to course

Custom Attribute Directives (Changing element appearance/behavior)

The Complete Angular Developer: From Zero to Hero

69. Custom Attribute Directives (Advanced)

We revisit custom attribute directives, focusing on how to manipulate multiple styles and handle complex inputs.

Scenario: Responsive Background Color

Create a directive that sets a default background color but allows overrides, and uses HostBinding to manage styles easily.

Using @HostBinding

@HostBinding is a property decorator that ties a property in the directive class directly to a property of the host element (the element the directive is applied to).

typescript // background.directive.ts import { Directive, HostBinding, Input, OnInit } from '@angular/core';

@Directive({ selector: '[appBackground]' }) export class BackgroundDirective implements OnInit {

// Input for default color (no alias) @Input() defaultColor: string = 'transparent';

// Input for optional override color @Input() appBackground: string = 'blue';

// Use HostBinding to bind the 'backgroundColor' style to an internal property @HostBinding('style.backgroundColor') backgroundColor: string = '';

ngOnInit(): void { // Initialize with the provided input or the default this.backgroundColor = this.appBackground || this.defaultColor; }

// Use HostListener to react to user actions @HostListener('mouseenter') mouseover() { this.backgroundColor = 'lightgray'; }

@HostListener('mouseleave') mouseleave() { this.backgroundColor = this.appBackground || this.defaultColor; } }

Usage

html

Blue Box

This pattern is cleaner than manually accessing ElementRef.nativeElement.style for every property.