Angular 4 - Enlace de eventos

En este capítulo, discutiremos cómo funciona Event Binding en Angular 4. Cuando un usuario interactúa con una aplicación en la forma de un movimiento del teclado, un clic del mouse o un mouseover, genera un evento. Estos eventos deben manejarse para realizar algún tipo de acción. Aquí es donde entra en escena la vinculación de eventos.

Consideremos un ejemplo para entender esto mejor.

app.component.html

<!--The content below is only a placeholder and can be replaced.-->
<div style = "text-align:center">
   <h1>
      Welcome to {{title}}.
   </h1>
</div>

<div> Months :
   <select>
      <option *ngFor = "let i of months">{{i}}</option>
   </select>
</div>
<br/>

<div>
   <span *ngIf = "isavailable; then condition1 else condition2">
      Condition is valid.
   </span>
   <ng-template #condition1>Condition is valid</ng-template>
   <ng-template #condition2>Condition is invalid</ng-template>
</div>
<button (click)="myClickFunction($event)">
   Click Me
</button>

En el app.component.html archivo, hemos definido un botón y le hemos agregado una función usando el evento click.

A continuación se muestra la sintaxis para definir un botón y agregarle una función.

(click)="myClickFunction($event)"

La función se define en el .ts archivo: app.component.ts

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

@Component({
   selector: 'app-root',
   templateUrl: './app.component.html',
   styleUrls: ['./app.component.css']
})

export class AppComponent {
   title = 'Angular 4 Project!';
   //array of months.
   months = ["January", "Feburary", "March", "April",
            "May", "June", "July", "August", "September",
            "October", "November", "December"];
   isavailable = true;
   myClickFunction(event) { 
      //just added console.log which will display the event details in browser on click of the button.
      alert("Button is clicked");
      console.log(event);
   }
}

Al hacer clic en el botón, el control llegará a la función myClickFunction y aparecerá un cuadro de diálogo, que muestra the Button is clicked como se muestra en la siguiente captura de pantalla:

Agreguemos ahora el evento de cambio al menú desplegable.

La siguiente línea de código lo ayudará a agregar el evento de cambio al menú desplegable:

<!--The content below is only a placeholder and can be replaced.-->
<div style = "text-align:center">
   <h1>
      Welcome to {{title}}.
   </h1>
</div>

<div> Months :
   <select (change) = "changemonths($event)">
      <option *ngFor = "let i of months">{{i}}</option>
   </select>
</div>
<br/>

<div>
   <span *ngIf = "isavailable; then condition1 else condition2">
      Condition is valid.
   </span>
   <ng-template #condition1>Condition is valid</ng-template>
   <ng-template #condition2>Condition is invalid</ng-template>
</div>

<button (click) = "myClickFunction($event)">Click Me</button>

La función se declara en el app.component.ts archivo -

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

@Component({
   selector: 'app-root',
   templateUrl: './app.component.html',
   styleUrls: ['./app.component.css']
})

export class AppComponent {
   title = 'Angular 4 Project!';
   //array of months.
   months = ["January", "Feburary", "March", "April",
            "May", "June", "July", "August", "September",
            "October", "November", "December"];
   isavailable = true;
   myClickFunction(event) {
      alert("Button is clicked");
      console.log(event);
   }
   changemonths(event) {
      console.log("Changed month from the Dropdown");
      console.log(event);
   }
}

El mensaje de la consola "Changed month from the Dropdown”Se muestra en la consola junto con el evento.

Agreguemos un mensaje de alerta en app.component.ts cuando el valor del menú desplegable se cambia como se muestra a continuación:

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

@Component({
   selector: 'app-root',
   templateUrl: './app.component.html',
   styleUrls: ['./app.component.css']
})

export class AppComponent {
   title = 'Angular 4 Project!';
   //array of months.
   months = ["January", "February", "March", "April",
            "May", "June", "July", "August", "September",
            "October", "November", "December"];
   
   isavailable = true;
   myClickFunction(event) { 
      //just added console.log which will display the event details in browser 
      on click of the button.
      alert("Button is clicked");
      console.log(event);
   }
   changemonths(event) {
      alert("Changed month from the Dropdown");
   }
}

Cuando se cambia el valor en el menú desplegable, aparecerá un cuadro de diálogo y se mostrará el siguiente mensaje: "Changed month from the Dropdown”.