Angular Event Binding

Angular Event Binding is basically used to handle the events like click, keyup, keydown, etc and which is define into the component html file.

Event Binding is used to bind data from DOM to the component.

There are some steps to define how to use

Step1) Suppose, you define addUser method into click event and template reference variable uname in input field in app-component.html file


<div class="container" align="center" style="margin-top: 20px;">
    <div class="row">
    <label>User Name </label>
    <input type="text" name="user_name" #uname/>
    </div>
    <div class="row" style="height: 10px;"></div>
    <div class="row">
    <input type="button" class="btn btn-primary" (click)="addUser(uname.value)" value="Add User" />
    </div>
    </div>

Step2) Now define addUser() method into the app-component.ts file


import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  userName : string ='';
  addUser(userName: string){
   console.log("userName:-"+userName)
  }
}

Step3) Now open the URL on the browser


http://localhost:4200/

Step4) When user file the username into textbox and click on the Add User button after that, you can get the output.