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;
  }

}

5 comments:


  1. It's interesting that many of the bloggers to helped clarify a few things for me as well as giving.Most of ideas can be nice content.The people to give them a good shake to get your point and across the command.
    Angularjs course in chennai

    ReplyDelete
  2. I have read your blog its very attractive and impressive. I like it your blog.

    mehndi design

    ReplyDelete
  3. Wow! Such an amazing and helpful post this is. I really really love it. It's so good and so awesome. I am just amazed. I hope that you continue to do your work like this in the future also relojes del ejército español

    ReplyDelete

Blogroll

Popular Posts