Open In App

Event handler in Angular 6+

Introduction:

In Angular 6, event handling is used to hear and capture all the events like clicks, mouse movements, keystrokes and etc. It is an important feature that is present in Angular and it is used in every project irrespective of its size.



Syntax:




<HTML element (event) > =  function name()>

Example 1: Using change:

app.component.html:




<input (change)="displayValue($event)">
<p> Entered Data is : {{data}}</p>

app.component.ts:




import { Component } from '@angular/core';     
@Component({     
  selector: 'app-root',     
  templateUrl: './app.component.html',     
  styleUrls: ['./app.component.css']     
})     
export class AppComponent {    
  data:String = '';  
  displayValue(event){
        this.data = event.target.value;  
  
  }  
}

app.module.ts:




import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
  
import { AppComponent } from './app.component';
  
  
@NgModule({
  imports:      [ BrowserModule, FormsModule ],
  declarations: [ AppComponent ],
  bootstrap:    [ AppComponent ],
  providers: []
})
export class AppModule { }

Output:


Example 2: Using onclick:

app.component.html:




<div>
  <button (click)="handleClick()">
    Tap Here to Display and Hide the Company name
  </button>
</div>
<br>
<div *ngIf="toDisplay" class="data">
  <div class="centered">
    {{name}}
  </div>
</div>

app.component.ts:




import { Component } from '@angular/core';
  
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['app.component.scss']
})
export class AppComponent  {
  name: string = '';
  
  toDisplay =false;
  
  handleClick() {
    this.toDisplay = !this.toDisplay
    this.name = 'GeeksForGeeks'
  
  }
  
   
}

app.module.ts:




import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
  
import { AppComponent } from './app.component';
  
  
@NgModule({
  imports:      [ BrowserModule, FormsModule ],
  declarations: [ AppComponent ],
  bootstrap:    [ AppComponent ],
  providers: []
})
export class AppModule { }

Output:

Before clicking the icon:

After clicking the icon:


Article Tags :