Search⌘ K
AI Features

Solution: Handle Events with a Custom Attribute Directive

Explore how to implement a custom attribute directive in Angular that handles mouseenter and mouseleave events. Learn to manipulate element styles dynamically and emit events to communicate changes, enhancing your app's interactivity and responsiveness.

We'll cover the following...

Solution

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

import { Directive, ElementRef, Input, OnChanges, OnInit, Output, EventEmitter, HostListener } from '@angular/core';

@Directive({
  selector: '[appAvatar]'
})
export class AvatarDirective implements OnChanges {

  @Input() size: number = 64;
  @Output() zoom = new EventEmitter<boolean>();

  constructor(private elementRef: ElementRef) {
  }

  @HostListener('mouseenter')
  onMouseEnter() {
    this.elementRef.nativeElement.style.transform = 'scale(1.1)';
    this.zoom.emit(true);
  }

  @HostListener('mouseleave')
  onMouseLeave() {
    this.elementRef.nativeElement.style.transform = 'scale(1)';
    this.zoom.emit(false);
  }

  ngOnChanges() {
    this.elementRef.nativeElement.style.width = this.size + 'px';
    this.elementRef.nativeElement.style.height = this.size + 'px';
  }
}
The task’s solution

Explanation

Key points to consider while implementing this exercise are:

  • How to react ...