Unit II
Unit II
Data binding is the most important feature of Angular. It allows for defining communication
between a component and the DOM. In Angular, there are two types of Data Binding.
Prerequisites
One-way data binding is unidirectional. You can only bind the data from component to the
DOM or from DOM to the component.
Interpolation:{{ value}}
app.component.ts file
In the above shared snapshot, I have one property, ‘CompanyName’, of type string which
will bind to the View, enclosed in double curly braces: {{property Name}}.
app.component.html file
Property binding is used to bind values to the DOM properties of the HTML elements.
Let’s consider an example for Property Binding which will create a property named as
‘companyWebsite’ of type string and assign value to that string.
app.component.ts file
app.component.html file
With the help of Event Binding, we can bind data from DOM to Component.
app.component.ts file
app.component.html file
1. In the TypeScript file, I have two properties - ‘companyBlogs’ of type string and
‘isShow’ of type boolean.
2. After that, in the HTML file, I have one click event, i.e., show().
3. We need to handle the show() event into TS file.
4. When the button is clicked, I am displaying the ‘companyBlogs’ value.
Two-Way Data Binding helps us to exchange data from both sides, i.e., from component to
view and from view to the component.
Have you ever heard the word ngModel and its famous ‘Banana In The Box’ syntax? The
syntax helps us quickly recognize how to properly write two-way data binding.
Let’s consider the below figure, which describes Banana In The Box syntax.
Let’s try to understand the above syntax by doing some code.
app.component.ts file
1. import { Component } from '@angular/core';
2.
3. @Component({
4. selector: 'app-root',
5. templateUrl: './app.component.html',
6. styleUrls: ['./app.component.css']
7. })
8. export class AppComponent {
9. email:string='';
10. constructor(){
11. }
12. }
app.component.html file
In order to use two-way data binding for form inputs you need to import
the FormsModule package in your Angular module. FormsModule provides additional
directives on form's elements, including input, select, etc. That's why it's required and this is
what the above line wants to say.
So, let’s import FormsModule into our app.module.ts file,