Databinding is a technique used in angular to exchange data between components and views. There are two different types of data-binding in angular. This will act as a bridge between components and view
- One way binding
- Two-way binding
One Way Binding
One-way binding is a technique which will bind data between components to the view. This system is unidirectional. Once we do any changes in the component then using one-way binding then it will update the HTML page.
Different types of one-way binding are
- String interpolation
- Event Binding
- Property Binding
- Attribute Binding
- Class Binding
- Style Binding
An example of one-way binding is given below, the component code looks like this below
export class AppComponent {
firstName: string = "Harikrishnan";
lastName:string = "R";
}
the view file can be edited like below
import { Component } from "@angular/core";
@Component({
selector: 'app-example',
template: `
<div>
<strong>{{firstName}}</strong>
<strong>{{lastName}}</strong>
</div>
`
})
Two-way binding
Two-way binding is a technique used in angular to send data from component to view and vice versa. This system is bidirectional. Two-way binding can be achieved using the ngModel directive.
An example of two-way binding is shown below
<input type="text" [(ngModel)] = 'value' />
Now we need to import in app.component.ts
import { FormsModule } from "@angular/forms";
and in the imports section in the app.component.ts
imports: [FormsModule]
import { Component } from '@angular/core';
@Component({
selector: 'app-search',
template: `
Enter the value : <input [(ngModel)] ='stringVal'>
<br>
Entered value is: {{stringVal}}
`
})
export class AppComponent {
stringVal: string = '';
}
I hope everyone got a small idea about the data binding techniques in angular. We will go into detail about the one-way binding technique in later blogs