Enter Your Email Address to Watch This Lesson

Your link to unlock this lesson will be sent to this email address.

Unlock this lesson and all 828 of the free egghead.io lessons, plus get Angular 2 content delivered directly to your inbox!



Existing egghead members will not see this. Sign in.

Just one more step!

Check your inbox for an email from us and click link to unlock your lesson.



Control Angular 2 Events with $event and Event Handlers

1:01 Angular 2 lesson by

This lesson talks about the benefits of using the parens-based (click) syntax so that Angular 2 can handle any custom event. Then the video explains how to pass in the actually event object using the familiar $event syntax.

Get the Code Now
click to level up

egghead.io comment guidelines

Avatar
egghead.io

This lesson talks about the benefits of using the parens-based (click) syntax so that Angular 2 can handle any custom event. Then the video explains how to pass in the actually event object using the familiar $event syntax.

If you need to get the actual MouseEvent, you can use the $Event syntax, which is just the same way we did it in Angular 1, so that the Event will be passed along.

simple.form.component.ts

@Component({
  selector: 'app-simple-form',
  template: `<div>

<input #myInput type="text">
<button (click)="onClick($event)">Click me!</button>
</div>`,
  styles: []
})
export class SimpleFormComponent implements OnInit {
  onClick(value) {
    console.log(value);
  }
  constructor() { }
  ngOnInit() {
  }
}

Now this value is the actual MouseEvent, so now when I click on this button, you'll see MouseEvent with all the properties you would expect from the MouseEvent.

MouseEvent

After that Event, you can go ahead and type myInput.value and as well say that this is the event, and we want to log out the event, and then the value, so the $Event is here, the myInput.value is here, and we're logging out the event and the value.

simple.form.component.ts

@Component({
  selector: 'app-simple-form',
  template: `<div>

<input #myInput type="text">
<button (click)="onClick($event, myInput.value)">Click me!</button>
</div>`,
  styles: []
})
export class SimpleFormComponent implements OnInit {
  onClick(event, value) {
    console.log(event);
    console.log(value);
  }
  constructor() { }
  ngOnInit() {
  }
}

Now when we click and I type something, Hello, and click, you'll see the MouseEvent and the value of Hello.

MouseEvent with Value

This will work on any DOM Event. If you were to say mouseover and hit save, now instead of onClick, every time I mouse over this button, you'll see those mouse events firing, and the value Hello of the form logging out as well.

HEY, QUICK QUESTION!
Joel's Head
Why are we asking?