WEB DEVELOPER SITE
PYTHONJAVAPHP7
 

Angular 4 Event Binding




Angular 4 event binding add some feature keyboard movement, a mouse click, or a mouseover, it generates an event.

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> days :
  <select>
     <option *ngFor = "let i of days">{{i}}
 </select>
</div>
<br/>

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

You can add event of click event.
(click)="myClickFunction($event)"

The function is defined in the .ts file: 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 days.
   days = ["Monday ", "Tuesday ", "Wednesday ", "Thursday", "Friday ", 
            "Saturday ", "Sunday "];
   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);
   }
}



We can add alert message in app.component.ts when the value from the dropdown is changed as shown here

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 days.
   days = ["Monday ", "Tuesday ", "Wednesday ", "Thursday", "Friday ", 
            "Saturday ", "Sunday "];
   
   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);
   }
   changedays(event) {
      alert("Changed day from the Dropdown");
   }
}