Welcome Guest! (App Version 3.1)

websitnero logo name

Event Binding

Event Binding in Angular

Event Bidning is also one-way binding just like -- String Interpolation and Property Binding. An event is attached to the HTML Element which when fired calls a functions what is written in the expression assigned to it. This way event is communciated from the view (.html) to the logic (.ts).

Practical Example of "String Interpolation"

Please follow the mentioned steps:

  1. Create a compennt named 'home'
  2. Add the home component in the app.component.html file removing all boilerplate code there.
  3. Create 1 variable of type :number which we will bind to logic and on click event, alert it. Also, lets make 2 functions each for mouseenter and mouseleave.
  4. Don't forget to add Forms Module for 2 way binding (ngModel) in app.module.ts

home.component.html

<input type="number" [(ngModel)]="someValue" />
<button (click)="alpha()">Click Me</button>

<hr/>

<p style="border:2px solid black;background:yellow;" 
(mouseenter)="beta($event)" (mouseleave)="ceta($event)">
  This is a paragraph.
</p>

home.component.ts

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

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {

  someValue: Number = 10;

  constructor() { }

  ngOnInit() {
  }

  alpha() {
    alert (this.someValue);
  }

  beta(ev) {
   ev.target.style.background = 'green';
  }

  ceta(ev) {
    ev.target.style.background = 'pink';
  }

}

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';

import { AppComponent } from './app.component';
import { HomeComponent } from './components/home/home.component';

@NgModule({
  declarations: [
    AppComponent,
    HomeComponent
  ],
  imports: [
    BrowserModule,
    FormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

  1. You'll get the following result.

WebsiteNero is highly optimized for learning various website developing technlogies. We try our best to add maximum modules and examples to help learn the concepts clearly and vividly. We try to present all content and examples as simple as we can removing any complexity to hurdle easy understanding. We try best provide you with worthful content, but we cannot guarantee full correctness of all the content on this site. While using this website, you agree to have read and accepted all our terms of use and conditions, cookie, and privacy policy. Copyright, 2013-2018 by websitenero.com. All Rights Reserved.