Event Binding and User Input in Angular

Introduction

We can have many user events such as clicking on a link, pressing buttons, etc. We can use Angular event binding to respond to any user clicks and events. Many DOM events are triggered when the user interacts with our application. We will see how event binding is performed in Angular. How $event works. We will see ways how to take input values using reference variables instead of $event object.

Event Binding 

Event binding in Angular is done using a DOM event. Surround the DOM event name with parenthesis() and assign it to a quoted statement of function. The statement in the quotes will respond to the event in parenthesis. 
<button  (click)="onBtnClick()">Save</button>

In the component.ts file, we will define the function onBtnClick() as follows:
export class HomeComponent {
  onBtnClick() {
    console.log("Button is clicked");
  }
}

$event Object

We can get user input using $event object. DOM events have a lot of important information. So we can use $event object to have access to this. Angular provides a DOM event object in the $event variable. We will pass the $event as a parameter to our event binding method. Now we will see this with an example where we will console log $event object. All standard DOM event objects have a target property which is a reference to the element on which event is raised.
event.target.value will give us the value of the <input> field.

@Component({
  selector: 'app-button',
  template: `
    <button (click)="onBtnClick($event)">
    Save 
   </button>
   <input>(keyup)="onKeyUp($event)   {{userInput}}'   })
export class AppButtonComponent { 
userInput: any;
  onBtnClick(ev) {
    console.log("Button was pressed", ev);
  }
 onKeyUp(ev){
   console.log(ev.target.value); // To print the user input
  this.userInput = ev.target.value;}
}

User Input with a template reference variable

We can get user data using Angular template variable. This technique is better as we can use this without knowing much about HTML implementation. We will have direct access to the HTML element using this technique. To define, precede a variable using the hash symbol(#). There is no need to write event.target.value. Instead, we will get the reference variable to have access to the value.

@Component({
  selector: 'app-button',
  template: `
     <input #userEntry (keyup)="onKeyUp()"/> // using template reference
     <div> {{userEntry.value}} </div> //getting value using template reference
'   
})
export class AppInputComponent {
}

Comments