Wednesday 29 April 2020

Angular 8 Session 17 - Custom Attribute Directive With Event Handler

Custom Attribute Directive With Event Handler

* A Custom Attribute Directives can listen into an event and act accordingly which extends custom directive features.

Implementing Event Handler
* Continuing with last example we have discussed (Part-16), text will be highlighted and bold based on an event fires with help of HostListener from angular/core library.
* HostListener is a decorator, which defines a DOM element with event to run when the event occurs. 
             For more details visit: https://angular.io/api/core/HostListener 
* @HostListener() takes 2 arguments:.
1. eventName
          2. args?
app.component.html
<div>
  <div appElementHighlighter>This tutorial elaborates custom directive</div>
  <br />
  <p appElementHighlighter>This is SKMDotNet Tutorial.</p>
</div>

app.component.ts

import { DirectiveElementRefHostListener } from '@angular/core';

@Directive({
  selector: '[appElementHighlighter]'
})

export class ElementHighlighterDirective {

  constructor(private erElementRef) { }

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

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

  private takeEffect(colorTypestring) {
    this.er.nativeElement.style.backgroundColor = colorType;
    this.er.nativeElement.style.fontWeight = 'bold';
  }
}

No comments:

Post a Comment

Angular 8 Session 21 - ngFor Directive In Angular

ngFor Directive Content will be resume soon. Stay tuned!