free
web stats

Angular 4 – How to Make Data Binding

In this post, We are going to lear how to data binding in Angular 4. This is one of the most important concepts in Angular. Data binding required in almost every anglular application.

If you don’t know how to create new angular 4 porject with angular-cli, please firstly apply this;

http://nbasercode.com/angular-cli/installation-angular-4-with-angular-cli/

Now, in app.component.ts file, I have defined a variable called title and I have set a value to app.component.html file.

In app.component.html file, we have a simple code like this;

<h1>
{{title}}
</h1>

Our title variable set in here {{ }}. That’s means interpolation. Interpolation means that this is the angular way of bind any variable data with the view. Our view page is app.component.html.

{{title}} this code is going to fetch out the data of inside the app.component.ts file. Then show this data on browser.

Now we are going to show multiple types of data whether is in JSON format or array or object or a reference to any external link.

Go to app.component.ts file and write this code inside export class Appcomponent’s code block

I’m creating an object named testObject and inside the object and three key; Id, name and age. I’m going to set id:1, name:Necip and age:30

Now I want to use this object in my view page but how? It is very simple, just write this for reach our object;

{{testObject.name}}

By the way; don’t forget to save your files 🙂

So How we can create array and pass this array to view page in Angular 4.

I want to create an array in my class(AppComponent).

testArray = [“cat”, “dog”, “horse”];

So how can I print all the values of this array?

One way is this and not a good practice;

{{testArray[0]}}
{{testArray[1]}}
{{testArray[2]}}

But if I don’t know how many objects are coming to our view. Another and most useful way is this;

<ul>
<li *ngFor =”let item of testArray”>{{item}}</li>
</ul>

ngFor; It is just like for each loop like other languages. testArray is an array and every time it’s going to store each value of that array in our variable item.

Here is our app.component.ts file;

app.component.html file;

We have seen how we can bind an array in our template. You can go this site and look at another methods for using data binding.

https://angular.io/api

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *