I am a Software Developer who enjoys writing code and solving problems. I write to share my understanding and insights about the topics that interests me and perhaps learn something new throughout this process.
Read it in 10 Mins
Is by Doing
If you've always wanted to learn how to use event binding in Angular, you've come to the right place. This article will discuss Angular's event binding and how to apply it to our Angular project. HubSpot estimates that Google receives 5.6 billion searches every day. Now that we think about it, everything that happens is predicated on user inputs, most notably clicks on the search button. Events are triggered after these actions are completed. With event binding in angular, we can leverage these events and their features. This post will detail event binding's advantages, different kinds of events, how to use it in an Angular project, and other subjects.
It is important to know why we need event binding in the first place. So, let us understand this with an example. When a user views a website, the user engages in various activities like clicking buttons, browsing pages, typing in input fields, and many more.
Therefore, all these user actions may be referred to as "events", where we use event binding to take some action (send a message, visit another website) when an event is triggered.
In its simplest form, an event is nothing but a listener that listens when there are changes:
Note, in the above event example, the target event gets bound using ‘(‘and‘)’. An Event is assigned to a statement triggered when a button click action is performed. Based on the HTML element we use, there are various events available to use, such as (keyup),
(submit) and so on. Angular determines an event target by determining whether the target event's name matches an event attribute of a recognised directive.
app.component.ts
public search() { return this.http.get(‘https://my-website.com/search’) }
In the example, we are making an HTTP call to our domain/server to get search results. Like this, we can do much more than just an http call.
Before we move ahead, it is recommended that you take the angular online training as this will help you learn about angular in a more practical way possible.
In Angular, there are two types of events when looked from a broad perspective;
The actions listed below can be taken in order to make an event passive. For instance, in the steps following, we'll make a scroll event passive.
#Step 1
Create a file zone-flags.ts under src directory.
#Step 2
Add the following line into this file.
content_copy
(window as any)['__zone_symbol__PASSIVE_EVENTS'] = ['scroll'];
#Step 3
In the src/polyfills.ts file, before importing zone.js, import the newly created zone-flags.
content_copy
import './zone-flags';import 'zone.js'; // Included with Angular CLI.
Look into the web application development course if you haven't already.
Template Statements have Side Effects. With a few minor exceptions, the syntax of template statements is quite similar to that of JavaScript expressions. Only when the relevant event fires do the statement become active. Therefore, it is important to avoid complex logic in using events and template statements, and keep them short and straightforward.
Statements cannot use Pipe (|). However, we can chain multiple methods or arguments using the operators ; and , we can include a method and pass an event reference or a template variable reference to execute logic after an event is fired.
Points to Remember
To know more about template statements, check here.
Template statements, as we just discussed, also support multiple handlers for a single event. Let us assume there comes a scenario where you want to have multiple tasks to perform based on a single event. You can add as many handlers as you want separated by ; (semi-colon) in the template statement while using event binding. You can check Multiple Event Handlers in action below:
For instance, in the above example, first the onAddItem() handler gets triggered, followed by assigning itemName = itemName.value
Note that the handlers or assignments happen in sequence.
DOM events have useful information about the event in $event payload. The context of the event, i.e the information in the $event varies according to DOM event. For instance, the event metadata for an input event and a click event are different. We can typecast the event in an angular component, perhaps preventing much of the information from being revealed. Below is an illustration that shows the same thing as we say:
Example: Before Type Casting
example.component.ts <input (click)="onClick($event)"> <p>{{values}}</p> example.component.ts onClick(event: any) { // without type cast this.values += event.target.value + ' | '; }
Example: After Type Casting (preferred approach)
onKey(event: MouseEvent) { // with type info this.values += (event.target as HTMLInputElement).value + ' | '; }
We generally use variables in an angular component and add our validation and business logic.
For example;
app.component.ts public title='Some variable in component!!'
However, if we need to use a variable within the template or view itself, the Template reference variable comes to our rescue.
A Template variable can be referred to as variables using “#” in the element, component, or directive you want to use.
Angular assigns a value to the template variable based on the context. If we declare in a HTML tag, value refers to that HTML element. If we declare it in a component, the value refers to the component instance.
app.component.html <input type="text" #name placeholder="Your name" /> <button type="button" (click)="submitName(name.value)">Submit Name</button>
In the above example, we are declaring a variable for an input element within a template and using its value in the submitName handler. Whenever a user clicks the Submit Name button, submitName handler gets fired.
Key events can be simply broken down into two words i.e Keys and Events. Keys annotates to physical keyboard keys and Events corresponds to the actions performed with the keys.
Key events can be used to have more control over the user’s interaction through text-based inputs.
In Angular, for example, the (key.enter) event binding is triggered when user presses and releases a key. Similar to these, there are other events supported in angular. Let us understand the key.enter with an example;
In angular, there are various ways to handle events. However, the following approaches are common in use:
1. Using $event Handler
app.component.html <input (keyup.enter)="keyHandler($event)" /> app.component.ts values: string = ''; keyHandler(event) { this.values = event.target.value; }
In the above example, we are using a handler with $event passed into it. The event information can be captured in the component and used to get the user input on the click of the enter button.
This is a convenient approach to using event binding. However, it is not the best practice to pass an entire $event as it can reveal too much information. To address this issue, a template reference can be used.
2. Using Template Reference Variable
app.component.html <input #name (keyup.enter)="userName = name.value" /> app.component.ts userName: string = '';
Here, we first declare the template variable in the input element and pass its value in the statement of the (key.enter) event. Also, we are directly mapping the value to a variable (userName) declared in the component.
So far, we have already discussed built-in events and all the different ways that angular may use them. Let us now examine the custom events in Angular:
Custom events are events that we can create within a component. These events are really useful when you have a nested component structure and want to pass data from one component to another. In order to implement custom events in Angular, you must have a parent-child component structure.
Consider an example, where we have a Card Component (parent component) and a Card Action Component (child component) and we want to share data from Card Action → Card Component.
To implement custom event binding, we will be using:
card-actions.component.ts import { Component } from '@angular/core'; @Component({ selector: 'card-actions', templateUrl: './card-actions.component.html', styleUrls: ['./card-actions.component.css'], }) export class CardActionsComponent { name = 'card-actions'; @Input() name: string; @Output() saveData: EventEmitter<any> = new EventEmitter<any>(); onSaveData(name: string) { // sending value to parent this.saveData.emit(name); } ngOnInit() { // Getting default value from parent console.log(this.name); } } card-actions.component.html <input #userName type="text"/> <button type="button" (click)="onSaveData(userName.value)">Save</button>
card.component.ts import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'], }) export class AppComponent { nameInParent: string = 'Default Value'; receiveName(name: string) { this.nameInParent = name; console.log('received value in parent', name); } } card.component.html <app-card-actions (saveData)="receiveName($event)" [name]="nameInParent"> </app-card-actions>
We hope you now have a clear understanding of how event binding in Angular may be used in angular in ways to strengthen codes like never before. Do check out KnowledgeHut Angular Online Training program to master in-depth concepts of Event Binding in Angular in the simplest ways possible.
Both property and event are used as one-way data binding in Angular, however property is used when we want to send data (either static or dynamic) from parent to the child component and event is used to fire event (on-click, keyup, any custom event) from child component which can be catched by parent component.
Event handler can simply be considered as a method or function that handles the event of specific HTML element.
For Eg:
<input (click)=”onClickName($event)” />
In this example, the on Click Name is the event handler that can listen to the target event that is clicked.
Name | Date | Fee | Know more |
---|