codeburst

Bursts of code to power through your day. Web Development articles, tutorials, and news.

Follow publication

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 to 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.

app.component.ts

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 agrument
changeName(myname: string): void {
this.name = myname;
}
}

app.component.html

<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.

app.component.html

<!-- passing the `$event` as an argument -->
<button (click)="handleMe($event)">click me</button>

app.component.ts

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

}

Similar tutorials

Conditional Rendering in Angular

Originally published at https://reactgo.com

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Published in codeburst

Bursts of code to power through your day. Web Development articles, tutorials, and news.

Written by Sai gowtham

JavaScript developer, writer my tutorials 🏗️ on reactgo.com , codeexamples.dev

No responses yet

Write a response