Check out our Angular Book Series.

How can you listen for a Browser Event in Angular?

This question recently came up in StackOverflow, and I thought I'd cross post my answer because I think I nailed this one.

The poster wanted to listen for an event in Angular. In the bulk of cases, I would do this in your HTML:


<button (click)="eventHandler($event)">

And this inside your component method:


eventHandler(event){
console.log(event);
}

It is simple, well documented, and Angular already 'wraps' the bulk of events dispatched up from your HTML page.

However, the poster really wanted to access the eventsin TypeScript. This is doable, but becomes a bit more complex.

First, add a #value to the HTML element in your HTML Template:


<button #myButton>

The #MyButton syntax allows you to reference the child in code using the @ViewChild metadata:


@ViewChild('myButton')
myButton: ElementRef;

Then you should be able to call the methods on the native element to access the event:


myButton.nativeElement.keydown();
myButton.nativeElement.keypress();
myButton.nativeElement.keyup();
myButton.nativeElement.blur();

If at all possible, I try to avoid drilling down into the ElementRef like this. I think I did it once when I created a reusable toast style component for a client, but for normal development I stick with the event directives.

Comments (Comment Moderation is enabled. Your comment will not appear until approved.)
All Content Copyright 2005, 2006, 2007, 2008, 2009 Jeffry Houser. May not be reused without permission
BlogCFC was created by Raymond Camden. This blog is running version 5.9.2.002.