The process of binding the events along with the methods is known as event binding. It is used with parenthesis ().
Example:
@Component({ selector: 'app-server', templateUrl: './server.component.html', styleUrls: ['./server.component.css'] }) export class ServerComponent implements OnInit { allowNewServer = false; serverCreationStatus= 'No Server is created.'; constructor() { setTimeout(() =>{ this.allowNewServer = true; }, 5000); } ngOnInit() { } } |
component.html file:
<p> Server is working fine. </p> <button class="btn btn-primary" [disabled]="!allowNewServer" >Add Server</button> <!--<h3 [innerText]= "allowNewServer"></h3>--> {{serverCreationStatus}} |
Output:
To bind an event with button:
To bind an event with a button, we are adding another method onCreation() in the component.ts file to call the event.
component.html file:
<p> Server is working fine. </p> <button class="btn btn-primary" [disabled]="!allowNewServer" (click)="onCreation()">Add Server</button> <!--<h3 [innerText]= "allowNewServer"></h3>--> {{serverCreationStatus}} |
Output:
Explanation:
In the above example, we are demonstrating event binding. Here, it will be displayed that the server is created, on clicking on the button.
To use data with Event Binding:
To understand the use of data with Event Binding, we are creating a method named “onNameUpdate”. We are then adding an event with it.
component.html file:
<label>Name of the Server</label> <input type="text" class="form-control" (input)="onNameUpdate($event)"> <p>{{serverName}}</p> |
component.ts file:
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-server', templateUrl: './server.component.html', styleUrls: ['./server.component.css'] }) export class ServerComponent implements OnInit { allowNewServer = false; serverName = ''; constructor() { setTimeout(() =>{ this.allowNewServer = true; }, 5000); } ngOnInit() { } onNameUpdate(event: Event) { this.serverName = (event.target as HTMLInputElement).value; } } |
Output:
Explanation:
In the above example, we are demonstrating the use of the $event to fetch the event’s data. The Angular dynamically updates it below the input, on typing anything in the block. Here, we are typing the name of the server which is dynamically displayed below the input.