Angular Event handling tutorial
In this tutorial, we are going to learn about how to handle the events in angular with the help of examples.
Listening events
To listen the events in angular we need to wrap the eventname
with a ()
parenthesis.
<!-- listening for the click event -->
<button (click)="handleClick()">Click me</button>
In the above code we are listening for the click
event on a button, so that whenever a user clicks on a button
the handleClick
method is invoked.
Passing arguments
Event handler methods can also accept arguments let’s see an example.
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
name = 'angular tutorial'; // at time of invocation we need to pass an argument
changeName(myname: string): void { this.name = myname; }}
<div>
<h1>{{name}}</h1> <!-- passing the argument to `changeName` method -->
<button (click)="changeName('gowtham')">Change name</button></div>
In the above code ,first we created a changeName
method with parameter myname
inside our app.component.ts
file, so that inside our markup we are passing the gowtham
as an argument to changeName
method.
Accessing the event object
To access the event
object in handler methods, we need to use the $event
variable let’s see an example.
<!-- passing the `$event` as an argument -->
<button (click)="handleMe($event)">click me</button>
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
handleMe(event:any){ //logging event object console.log(event) }
}