Angular 4 - Associação de Evento

Neste capítulo, discutiremos como a Event Binding funciona no Angular 4. Quando um usuário interage com um aplicativo na forma de um movimento do teclado, um clique do mouse ou um mouseover, ele gera um evento. Esses eventos precisam ser manipulados para executar algum tipo de ação. É aqui que a associação de eventos entra em cena.

Vamos considerar um exemplo para entender melhor isso.

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>

No app.component.html arquivo, definimos um botão e adicionamos uma função a ele usando o evento click.

A seguir está a sintaxe para definir um botão e adicionar uma função a ele.

(click)="myClickFunction($event)"

A função é definida no .ts Arquivo: 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);
   }
}

Ao clicar no botão, o controle virá para a função myClickFunction e uma caixa de diálogo aparecerá, que exibe the Button is clicked como mostrado na imagem a seguir -

Vamos agora adicionar o evento de mudança ao menu suspenso.

A linha de código a seguir o ajudará a adicionar o evento de mudança ao menu suspenso -

<!--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>

A função é declarada no app.component.ts arquivo -

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);
   }
}

A mensagem do console “Changed month from the Dropdown”É exibido no console junto com o evento.

Vamos adicionar uma mensagem de alerta em app.component.ts quando o valor da lista suspensa é alterado conforme mostrado abaixo -

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");
   }
}

Quando o valor no menu suspenso é alterado, uma caixa de diálogo aparecerá e a seguinte mensagem será exibida - “Changed month from the Dropdown”.