Thursday, 7 June 2018

Angular - Attribute - Respond to user-initiated events

Currently, appHighlight simply sets an element color. The directive could be more dynamic. It could detect when the user mouses into or out of the element and respond by setting or clearing the highlight color.
Begin by adding HostListener to the list of imported symbols.
src/app/highlight.directive.ts (imports)
import { Directive, ElementRef, HostListener } from '@angular/core';
Then add two eventhandlers that respond when the mouse enters or leaves, each adorned by the HostListener decorator.
src/app/highlight.directive.ts (mouse-methods)
@HostListener('mouseenter') onMouseEnter() {
  this.highlight('yellow');
}

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

private highlight(color: string) {
  this.el.nativeElement.style.backgroundColor = color;
}
The @HostListener decorator lets you subscribe to events of the DOM element that hosts an attribute directive, the <p> in this case.
Of course you could reach into the DOM with standard JavaScript and attach event listeners manually. There are at least three problems with that approach:
  1. You have to write the listeners correctly.
  2. The code must detach the listener when the directive is destroyed to avoid memory leaks.
  3. Talking to DOM API directly isn't a best practice.
The handlers delegate to a helper method that sets the color on the host DOM element, el.
The helper method, highlight, was extracted from the constructor. The revised constructor simply declares the injected el: ElementRef.
src/app/highlight.directive.ts
import { Directive, ElementRef, HostListener } from '@angular/core';

  selector: '[appHighlight]'
})
export class HighlightDirective {
  constructor(private el: ElementRef) { }

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

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

  private highlight(color: string) {
    this.el.nativeElement.style.backgroundColor = color;
  }
Run the app and confirm that the background color appears when the mouse hovers over the p and disappears as it moves out.











No comments:

Post a Comment