C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Angular 7 Event BindingAngular facilitates us to bind the events along with the methods. This process is known as event binding. Event binding is used with parenthesis (). Let's see it by an example: @Component({ selector: 'app-server2', templateUrl: './server2.component.html', styleUrls: ['./server2.component.css'] }) export class Server2Component implements OnInit { allowNewServer = false; serverCreationStatus= 'No Server is created.'; constructor() { setTimeout(() =>{ this.allowNewServer = true; }, 5000); } ngOnInit() { } } component.html file: <p> Server2 is also working fine. </p> <button class="btn btn-primary" [disabled]="!allowNewServer" >Add Server</button> <!--<h3 [innerText]= "allowNewServer"></h3>--> {{serverCreationStatus}} It will give an output that "No Server is created". Now, we are going to bind an event with button. Add another method onCreateServer() in component.ts file which will call the event. component.html file: <p> Server2 is also working fine. </p> <button class="btn btn-primary" [disabled]="!allowNewServer" (click)="onCreateServer()">Add Server</button> <!--<h3 [innerText]= "allowNewServer"></h3>--> {{serverCreationStatus}} Output: Now, after clicking on the button, you will see that it is showing server is created. This is an example of event binding. How to use data with Event Binding?Let's understand it by an example. Here, we will create a method named "onUpdateServerName" and add an event with it. component.html file: <label>Server Name</label> <input type="text" class="form-control" (input)="OnUpdateServerName($event)"> <p>{{serverName}}</p> component.ts file: import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-server2', templateUrl: './server2.component.html', styleUrls: ['./server2.component.css'] }) export class Server2Component implements OnInit { allowNewServer = false; serverName = ''; constructor() { setTimeout(() =>{ this.allowNewServer = true; }, 5000); } ngOnInit() { } OnUpdateServerName(event: Event) { this.serverName = (<HTMLInputElement>event.target).value; } } Output: You can see that when you type anything in the block, it dynamically updates it below the input. This is how we can use $event to fetch the event's data.
Next TopicAngular 7 Property Binding
|