Event Binding
Ex1:- Listening to the click events
1) app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
@NgModule({
imports: [BrowserModule],
declarations: [AppComponent],
bootstrap: [AppComponent]
})
export class AppModule {
}
2) app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template: `<div><h1>{{message}}</h1><button (click)="showMessage()"/></div>`
})
export class AppComponent {
message: string = '';
showMessage() {
this.message = 'Angular – Event Binding';
}
}
Ex2:- listening to the keyboard events
1) app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
@NgModule({
imports: [BrowserModule],
declarations: [AppComponent],
bootstrap: [AppComponent]
})
export class AppModule {
}
2) app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'event-binding-app',
template: `
<div>
<h1>{{message}}</h1>
<input type="text" (keypress)="showMessage($event)"/>
</div>
`
})
export class AppComponent {
message: string = 'Angular – Event Binding';
showMessage(onKeyPressEvent: KeyboardEvent) {
this.message = (<HTMLInputElement>onKeyPressEvent.target).value;
}
}