What is data Binding in Angular 12
Deepa Chaurasia
Posted on June 18, 2022
Data Binding is communication between typescript code of your component and the template (html) the user see.
Data Binding === Communication
We get different ways of communication.
Let's say we want to output data from our Typescript code in html template. We can use String Interpolation for that.
Syntax for String Interpolation
You put it inside double curly braces.
So in your ts file you have a property name of string type and set to 'deepa'
Example of String Interpolation
In your ts file:
Now in your html you will use it like this:
So it will print 'My name is Deepa'
Now suppose you have a button to submit the form or some other task. It must be enabled only if you're admin. Whether you're admin or not buisness logic will be handled on your ts file.
In this case what you can use is Property Binding
The native property [disabled] of html file will get bind to a boolean value that will come from ts file .
Example of Property Binding
In ts file:
I have defined a property isAdmin like this and set it to true. Now in my html file
- Now if user is not admin ,then button will be disabled otherwise it's enabled.
- As we are having isAdmin **set to true so it's **enabled.
Event Binding
It allows your component to react to user's actions such as button clicks ,key strokes and many more.
Like Property Binding use [] Square Brackets
Similarly Event Binding use () paranthesis.
Let's say If i click on a button 'Add' only then data will be binded to html template.
You can use Event Binding here like this:
In your ts file
here you can see,initially name is not set to 'deepa' but inside onClick() method we are doing that.
We'll call this method by event binding like this:
Here in this case,name will set to 'deepa' only after calling the method this is called event binding.
Thanks for reading,Please like share and save if it helped you :)
Posted on June 18, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
May 30, 2022