Angular2 provides EventEmitter class.  We can use this EventEmitter class in component and directives to trigger custom events. Lets take a scenario and implement custom event.
Source Code          DEMO

Scenario

Trigger event on input field when user stops typing instead of change event. 

Analysis

Catch keyup event on the input field, take some timeout to trigger event, If user types any thing in this delay, cancel before timeout and create new timeout to trigger event.

Directive

Lets create directive for above scenario. Observe onUserStopTyping variable, it emits the event when user stops typing
import { Directive, Output, HostListener, EventEmitter } from '@angular/core';

@Directive({ selector: '[customEvent]' })
export class CustomEventDirective {
  @Output() onUserStopTyping = new EventEmitter();
  _timeout: any = null;
  val: string = '';

  @HostListener('keyup', ['$event']) onChange(event: any) {
    if(this._timeout){ //if there is already a timeout in process cancel it
       clearTimeout(this._timeout);
    }
    this.val = event.target.value;
    this._timeout = setTimeout(()=>{
       this._timeout = null;
       this.onUserStopTyping.emit({
          value: this.val
       });
    },1000);
  }
}

app.component.ts

Here we are using above CustomEventDirective
import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  template: `
    <h2>Type something in below textbox</h2>
    <div>Value : <b>{{value}}</b><div>
    <input customEvent (onUserStopTyping)="changeValue($event)"/>
  `
})
export class AppComponent {
  value: string = '';

  changeValue(event: any) {
    this.value = event.value;
  }

}

0 comments:

Blogroll

Follow this blog by Email

Popular Posts