Data Binding In Angular
In this article, We will learn how data binding works in Angular with examples. If no dynamic data is displayed, Angular Components are worthless. They must also react to events and respond to user interactions. The data binding keeps both the component and the view in sync. To bind data, we employ techniques like interpolation, property binding, event binding, and two-way binding. We also learn how to use the ngModel directive in Angular Forms to achieve two-way binding.
What is Angular Data Binding
Data binding is a method of synchronizing data between the component and the display. Angular refreshes the component whenever the user updates the data in the view. Angular refreshes the view when the component receives new data.
Data binding has numerous applications. You can dynamically present models to the user. Change the style of elements, respond to user interactions, and so on.
Data Binding in Angular
In Angular, data binding may be divided into two categories. Binding in one direction or two directions
One way binding
Data flows from one direction in one-way binding. Either from component to view or from view to component.
Interpolation:
We can use interpolation to incorporate expressions as part of any string literal in our HTML. The expressions are evaluated into a string, which is then replaced in the original string and the view is updated. Interpolation is available anywhere a string literal is used in the view.
The interpolation is indicated by the {{}} (double curly brackets) in the Angular template. The syntax is as follows:
{{ templateExpression }}
- <span>Welcome, {{firstName}} {{lastName}}</span>
Update your app.component.ts looks like below:
- import { Component } from '@angular/core';
- @Component({
- selector: 'app-root',
- templateUrl: './app.component.html',
- styleUrls: ['./app.component.css']
- })
- export class AppComponent {
- firstName= "Jignesh";
- lastName= "Patel"
- }
Property binding
- [binding-target]=”binding-source”
- <h1 [innerText]="title"></h1>
- <h2>Example 1</h2>
- <button [disabled]="isDisabled">I am disabled</button>
- @Component({
- selector: 'app-root',
- templateUrl: './app.component.html',
- styleUrls: ['./app.component.css']
- })
- export class AppComponent {
- title="Angular Property Binding Example"
- //Example 1
- isDisabled= true;
- }
Two Way binding
- <Element [(someProperty)]="value"></Element>
ngModel
- import { FormsModule } from '@angular/forms';
- <input type="text" name="value" [(ngModel)]="value">