Show List
Data Binding
There are two types of data binding available in Angular one way and two way
One way data binding
This is used to access the data field (model data) and display on the HTML page (view). Double curly brackets {{}} are used (also called interpolation) for this.
Example:
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 {userName: string = "";constructor() { }ngOnInit(): void {this.userName = "";}showMsg(){alert("Event Triggered")}updateUserName(e: any){this.userName = (e.target as HTMLInputElement).value;}}
home.component.html
<button (click)="showMsg()"> Demo </button><br><br><input type="text" (input)="updateUserName($event)"><br>{{userName}}
Two way data binding
In this the model data can also be updated by changing the data on the view. This is achieved using [(ngModel)] directive (Also called banana in the box).
In order to use ngModel, need to import the FormsModule package in the Angular module
home.component.html
<button (click)="showMsg()"> Demo </button><br><br><input type="text" [(ngModel)] ="userName" ><br>{{userName}}
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 {userName: string = "";constructor() { }ngOnInit(): void {this.userName = "";}showMsg(){alert("Event Triggered")}}
app.module.ts
import { NgModule } from '@angular/core';import { FormsModule } from '@angular/forms';import { BrowserModule } from '@angular/platform-browser';import { AppComponent } from './app.component';import { HomeComponent } from './home/home.component';@NgModule({declarations: [AppComponent,HomeComponent],imports: [BrowserModule,FormsModule],providers: [],bootstrap: [AppComponent]})export class AppModule { }
When the text is entered in the input field, the updated value gets displayed under the input element.
London
London, the capital of England and the United Kingdom, is a 21st-century city with history stretching back to Roman times.
Paris
Paris, France's capital, is a major European city and a global center for art, fashion, gastronomy and culture. Its 19th-century cityscape is crisscrossed by wide boulevards and the River Seine.
Tokyo
Tokyo, Japan’s busy capital, mixes the ultramodern and the traditional, from neon-lit skyscrapers to historic temples. The opulent Meiji Shinto Shrine is known for its towering gate and surrounding woods.
Source Code:
https://github.com/it-code-lab/angular-application
Leave a Comment