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.
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; } }
ReplyDeleteIt'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
I have read your blog its very attractive and impressive. I like it your blog.
ReplyDeletemehndi design
It's great that you share with us.
ReplyDeletedream girls
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
ReplyDeleteThank you for sharing the post.
ReplyDeleteSponsorship in Bahrain