Edupala

Comprehensive Full Stack Development Tutorial: Learn Ionic, Angular, React, React Native, and Node.js with JavaScript

Angular events binding and Angular event list

angular events

Angular events binding is one type of data binding in Angular. Angular data binding allows us to sync data between the component properties and the view on the template. The data binding helps bring or update data in component typescript code to the view or vice versa.

In this tutorial, we’ll learn how to use event binding, different types of events available in an Angular, and demonstrate a few examples of it. Let’s get started.


What are Angular events or Angular event binding?

Angular event binding is a type of one-way data binding, where data flow from view in a template to data source in a component typescript file. Event binding allows us to listen to certain events such as clicks, touches, keystrokes, and mouse movements so that we can respond to this event. In Angular we have different data binding as shown in the figure below, we had already covered two-way data binding in the previous tutorial.

Angular events
Angular data binding

Angular event binding syntax

Angular event binding syntax consists of a  target event name within parentheses on the left and a quoted template statement on the right. The statement can be an expression or invoking method. In invoking, the method can with and without argument, if any argument, then we can pass any number of arguments.

<some-element (eventName)="expression">
  Invoke someMethod on some event
</some-element>

<some-element (eventName)="someMethod()">
  Invoke someMethod
</some-element>

<some-element (eventName)="someMethod(parameter1, parameter2)">
  Invoke someMethod with parameters
</some-element>

// Example
<button (click)="update()">Submit</button>

Note: Remember, parentheses represent event binding and square brackets represent property binding.

In the above example, on the button tag, we add an event (click) to define what should happen when the button is clicked. When the (click) event happens we call we want to tell Angular to respond to the click event on the button, by invoking the update() method.

Angular event binding syntax

Angular event binding has the following parts:

  1. The host element is the source of events for the binding.
  2. The event name is what type of event to bind to the host element
  3. Expression is evaluated when the event is triggered, it can be an expression or method with and without parameters.

Angular Event binding simple example

In our first example of Event binding, we have a named variable containing ‘Keanu Reeves’ and it will display on the screen. We have a button, whenever we click on the Change name button it will invoke changeName() method and updates the value of the variable name to John Wick using a one-way event binding to the method the changeName(). The new updated name John Wick will render on screen.

@Component({
selector: 'app-root',
template:`
<h1>{{name}}</h1>
<button (click)="changeName()">Change name</button>
`
})
export class AppComponent {
   name: string = "Keanu Reeves";

  changeName() {
    this.name = "John Wick";
   }
}

Angular events example: Angular click event

We have got some idea about Angular event binding, let’s demonstrate a simple example of an Angular click event. Here is a screenshot of our first example of angular event binding.

angular events or angular click event
Angular event binding

We have num variable property from component typescript file, and we have two-button with Angular click event. Clicking on increment will add a number by one and clicking on decrement will subtract a number by one. Let’s first define the num in the component typescript file.

import { Component } from '@angular/core';
.....
export class AppComponent {
  num = 1;
}

Now in our component template, let’s add two buttons with Angular click event.

<section>
  <h3>Angular event binding</h3>
  <div>
    Value on number on click event <span class="num-large">{{ num }}</span>
  </div>

 <button class="btn btn-success" (click)="num = num + 1">Increment ++</button>
 <button class="btn btn-danger" (click)="num = num - 1">Decreament --</button></section>

We used bootstrap for this UI, if you want to know the best approach for adding Bootstrap in Angular, then we have already covered a tutorial on it.


Types of Angular event listener or Angular events list

In the above example, we have learned the Angular click event. In native HTML or in Angular we have plenty numbers of options to add an Angular event listener. Here we have listed some of the most popular and common Angular event listeners in Angular.

Event nameDescription
(click)The click event occurs when an element is clicked.
(change)The change event is triggered when change occurs on the binding elements, like select, Textarea, input, and other elements.
(dblclick)The double-click event occurs when an element is clicked two times.
(blur)The blur event fires when an element has lost focus. 
(submit)The submit event fire when clicking on the button or inputting with type submit.
(focus)The focus event fires when an element has received focus
(scroll)The scroll event fires when the document view has been scrolled.
(keyup)When a user presses and releases a key, an event occurs and is mostly used with input fields. It is one of the keyboard events.
(keydown)The keydown event is fired when a key is pressed. It is one of the keyboard events.
(keypress) The keypress event is fired when a key that produces a character value is pressed down. It is one of the keyboard events.
(mousedown)The mousedown event is fired at an Element when a pointing device button is pressed while the pointer is inside the element and is a mouse event.
(mouseup)The mouseup event occurs when a user releases a mouse button over an element and is a mouse event.
(mouseenter)The mouseenter event occurs when the mouse pointer is moved onto an element and is a mouse event.
(mouseleave)The mouseleave event occurs when the mouse pointer is moved out of an element and is a mouse event.
(mousemove)The mousemove event occurs when the pointer is moving while it is over an element and is a mouse event.
(mouseover)The mouseover event occurs when the mouse pointer is over the selected element and is a mouse event.
(mouseup)The mouseup event occurs when a user releases a mouse button over an element and is a mouse event. 
(copy)The copy event occurs when the user copies the content of an element. 
(paste)The past event occurs when the user pastes the content of an element. 
(cut)The cut event occurs when the user cuts the content of an element. 
(drag)The drag event occurs when an element or text selection is being dragged
(drop)The drop event occurs when dragged data is dropped.
(dragover)The dragover event occurs when a draggable element or text selection is being dragged over a valid drop target. 
(input)The input event occurs when an element gets user input
Angular events list

Angular $event object

The angular event objects $event has the get details information about an event. This $event is a special variable, that represents the thing emitted. Here we’ll demonstrate a simple example of it.

Angular $event object
Angular event listener

In this example we have input and a button, on clicking on the button we are sending two-parameter, the first is $event object and a second value of the input box. We can see above in the image, event objects have detailed information about the event emitted.

<div class="form-group">
 <label for="exampleInputEmail1">User name</label>
 <input class="form-control" [(ngModel)]="name" 
    name="name" #nameCtrl="ngModel">
   <button class="btn btn-success" (click)="clickEvent($event, nameCtrl.value)">
        Submit
   </button>
</div>

In the typescript component file, let’s define a method that we want to invoke when the user clicks on submit button.

....
export class AppComponent {
  name = '';

  clickEvent(event: Event, name: string) {
    console.log('Input name value: ' + name)
    console.log(event);
    debugger
  }
}

Angular event example on the select element

In our last example, we’ll invoke the Angular change event on select input, here is a screenshot of the Angular change event.

angular change event example
<div class="form-group">
  <label>Select favouritcountry</label>
  <select (change)="selectedCountry($event)" class="form-control">
    <option value="india" selected="selected">India</option>
    <option value="france">France</option>
    <option value="germany">Germany</option>
    <option value="canada">Canada</option>
  </select>
</div>
selectedCountry(event: any) {
  console.log(event.target.value);
}

Angular mouse events

In the Angular event list we can see, lots of events available in Angular. Let’s demonstrate Angular mouse events on the div element. Whenever the mouse moves over the div, we called an event mouseOver which in turn invokes a method over where we change the variable mouseOverDiv to true. And on mouseOut event we called out a method to change mouseOverDiv to false .based on it we change the variable.

Based on the value of mouseOverDiv we change the div element background and font-weight value and here is a screenshot of our example.

Angular mouse events
Angular mouse events
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
    <div class="container"
      (mouseover)="over()"
      (mouseout)="out()"
      [ngClass]="mouseOverDiv ? 'div-in' : 'div-out'"
    >
      Angular mouse events : mouseOver and mouseOut
    </div>
  `,
  styleUrls: ['./app.component.scss'],
})
export class AppComponent {
  mouseOverDiv: boolean = true;

  over() {
    this.mouseOverDiv = true;
  }

  out() {
    this.mouseOverDiv = false;
  }
}

Led add CSS style for our above example of Angular mouse events.

.container {
    padding: 20px;
    height: 50px; 
    width: 400px; 
    background: #e2e2e2
}

.div-in {
    background: blue;
    font-weight: bolder;
}

.div-out {
    background-color:#e2e2e2;
    font-weight: 400;
}

Angular key events

Like the mouse, we can have Angular key events and in our previous example, we have seen a key event on Click. In keyup event, whenever the keyboard key is pressed and released we invoke an event to handle it. The keyup event is mostly used on the input element and here is a screenshot of the Angular key up event example.

Angular key events
Angular key events
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
    <div class="container">
      <input (keyup)="onKeyUp($event)" />
      <p>Value of inputData : {{ inputData }}</p>
    </div>
  `,
  styleUrls: ['./app.component.scss'],
})
export class AppComponent {
  inputData: string = '';

  onKeyUp(event: any) {
    this.inputData = event.target.value;
  }
}

Conclusion
We have completed, Angular event binding and we can use a custom event emitter to communicate between child to parent components using the @Ouput() decorator.

Check articles on the best and latest 2022, and 2021 Angular books to read for your journey from beginner to advanced level. BEST BOOK ON ANGULAR 2022 – 2021

Related Post

Angular events binding and Angular event list

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top