Search⌘ K

Solution: Pass Values to the Custom Attribute Directive

Understand how to pass values such as color modes and optional sizes to custom attribute directives in Angular. This lesson helps you implement Input properties to control styling dynamically, enhancing your Angular components with flexible and reusable directives.

We'll cover the following...

Solution

Here’s a possible implementation of what the solution for this task may look like:

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

@Directive({
  selector: '[appButton]'
})
export class ButtonDirective implements OnChanges {

  @Input('appButton') color!: 'primary' | 'secondary';
  @Input() size: number = 120;

  constructor(private elementRef: ElementRef) {
  }

  ngOnChanges() {
    this.elementRef.nativeElement.style.width = `${this.size}px`;

    if (this.color === 'primary') {
      this.elementRef.nativeElement.style.backgroundColor = 'deepskyblue';
      this.elementRef.nativeElement.style.color = 'white';
    }

    if (this.color === 'secondary') {
      this.elementRef.nativeElement.style.backgroundColor = 'gold';
      this.elementRef.nativeElement.style.color = 'black';
    }
  }
}
The task’s solution

Solution explained

We need to use Input properties in the directive to pass the color mode data ...