*ngIf and *ngFor can help you keep your Angular code clean, simple, and effective. So, let's learn what *ngFor and *ngIf are all about.
What is *ngFor?
Let's talk about *ngFor first. You use the *ngFor directive to traverse over an array object and display the data in the UI.
Let me give you an example of how it works:
I have an array of objects here that contains people's names and their ages.
Now, we will use *ngFor to display these names in the interface.
First, create an Unordered List tag, and inside that create a List tag, like this:
Then, we will use *ngFor in the List tag, just like in the example below:
In this example, we are creating an item using the keyword of the array. It will iterate over each item in the array, and will print out the item name and item age, or any other object key we have in the array object.
You will see the above output when you save. That is because we have 8 items in the array. So, we we get 8 items in our list tag. But it is static data, so let's change it to dynamic.
Here, we are using and in two curly brackets. This is called interpolation, and it's how we show data in the HTML template.
Save the file, and you will see the following:
We can also do something like this:
So, in this example, we are showing the list in a different format. If you save, you will see the following output:
What is *ngIf?
You use the *ngIf directive in Angular to show some data or item based on some condition.
Let's say we are calling an API. We show some message that the data is loading while the application fetches the data from the API, because it can take some time depending on the server. And when the API call finishes, we show the data.
In this case, we can use *ngIf.
Let me give you an example of how this works:
Here, we show the array data in the template.
Now, let's create a button and give it a title of Click to Hide List.
Now, in the TypeScript file, create a boolean variable called :
Initially, the value of isVisible is true. Also, create a function called that will change the value of to false if triggered.
On the click of the button that we created, we will run this function:
So, every time the button is clicked, this function will run. This will change the value of to false from true.
Now, let's use *ngIf to show our array list when is true.
If you click the Hide List button, the list will hide, and you will see only the button.
We can also change the value to something like this:
So, if the value is true, it will change to false. And if the value is false, it will change to true. In other words, this function will toggle the value of .
Congratulations! Now we have learned how to use *ngFor and *ngIf in Angular.
So go ahead, and experiment with it a bit. There are tons of things you can do.
You can check out my video on Angular *ngFor and *ngIf explained in 10 Minutes, which is on my YouTube channel.
Feel free to download the code here: https://github.com/nishant-666/Angular-ngFor-and-ngIf
If you read this far, tweet to the author to show them you care. Tweet a thanks
Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started
In this post we are going to go over the core directive, namely we are going to go over the following:
- what does and what is its syntax
- What are the most common errors associated to
- Variable visibility
- Finding the index position of an element
- How to stripe a table using and
- Identifying the and the element of a list
- How does track items, why it can be important for performance?
- How to use ?
- When to use ?
- Learn why is not only for arrays
- A quick question for you at the end about learning
So let's get started diving into ! Below you can also find a video version of this post if you prefer, and the running code of this post is available here.
The ngFor features are also covered in this video, have a look:
What can we do with ?
The core directive allows us to build data presentation lists and tables in our HTML templates. Let's take for example the following data:
With we can print this data to the screen under the form of a data table, by generating HTML similar to this:
What is the syntax of ?
To use , let's create a component so that we can have a working HTML template:
This template will generate the HTML table that we showed just above. We can see in this example the (most common) syntax for using :
- we are passing to an iteration expression
Note that the loop variable is only visible inside the loop, you would not be able to access it outside the section.
Common Errors to watch out for
If you have an AngularJs background, you will see this error a few times before you get used to the new Angular syntax:
This is because you have accidentally either used instead of , or forgot to add the keyword at the beginning of the expression:
Finding the index of a list element
A very common requirement is to add to a list the numeric index position of its element. We can get the index of the current element by using the variable:
Note that you need the let keyword to get the value of the index, otherwise you will get an error similar to this one:
With this change, the HTML generated now looks like the following:
How to stripe a table using and
Another very common functionality needed when building tables is to be able to stripe a table by adding a different css class to the even or odd rows.
Let's say that to the above table we want to add a CSS class if the row is even and the CSS class if the row is odd.
In order to so, we have a couple of variables available for that: and , that can be used in the following way together with :
Let's have a look at the HTML generated by this template:
As we can see, added the CSS classes to the right rows, as we would expect.
Identifying the and the element of a list
Just like the even and odd functionality, there are also two other variables that can be used to identify the first and the last elements of the list:
This will add a CSS class named to the first element of the list, and a CSS class named to the last element of the list:
How does work when we add or remove elements from the list?
As the input list gets modified, will try to avoid to constantly create and destroy the DOM elements of the list, as this is an expensive operation. Also, when we pass to a new list, this does not mean that the whole list will be re-built, meaning all the DOM re-created.
Many of the existing DOM elements will be reused and only some values inside them will be overwritten, and the decision is taken for each element in the list separately.
In order to take that decision Angular needs to identify each list element in a unique way, because for example if we pass in a new list with a different order, Angular will try to identify the elements and re-order the DOM elements of the list without deleting them and recreating them.
How are list items tracked by default?
by default tracks list items using object identity. This means that if you build a list of new objects from scratch with the exact same values as the previous list and pass this newly built list to , Angular will not be able to tell that a given list item is already present or not.
From a point of view of object identity, the new list contains a whole new set of items, completely different from the previous set. This is the case if for example we query the data again from the backend.
Tracking by object identity is a good default strategy because Angular has no information about the object so it cannot tell which property it should use for tracking.
Why can this be important for performance?
As we see, already does a lot of optimizations out-of-the-box to try to reuse existing DOM elements as much as possible, but it's doing so based on object identity.
In the case of templates with large lists, or lists that occupy a large part of the screen, we might even with those optimizations still run into performance issues and notice that the UI is slow due to the large amount of DOM elements being created and destroyed.
If that happens to be the case, we can configure to do the tracking by something else other than object identity.
How to use ?
We can provide our own mechanism for tracking items in a list by using . We need to pass a function to , and the function takes a couple of arguments, which are an index and the current item:
This implementation would do the tracking based on the property.
When to use ?
The use of it's a performance optimization and is usually not needed by default, it's in principle only needed if running into performance issues.
Let's say that you are shipping to ancient mobile browsers or ancient versions of IE: you might want to consider applying as a precaution in your larger tables, but it really depends on your system and the use case.
Is only For Arrays?
We can now use this configuration element in our template in the following way:
Now let's query this data from the configuration elements using :
Do you see what happened here? Turns out the is a class that is part of Angular and is itself an Iterable! So although we can use it programmatically in the component class, we can also pass it directly to and iterate over it directly.
And the same could be done with any other Iterable in our program.
I hope you enjoyed the post, I invite you to have a look at the list below for other similar posts and resources on Angular.
And if you would like to know about more advanced Angular Core features like ngFor, we recommend checking the Angular Core Deep Dive course, where we cover all the Angular core directives in great detail.
I invite you to subscribe to our newsletter to get notified when more posts like this come out:
If you are just getting started learning Angular, have a look at the Angular for Beginners Course:
Other posts on Angular
If you enjoyed this post, have also a look also at other popular posts that you might find interesting:
Before you can do that To complete this action, sign in to your Community account or create a new one.
NgFor is a built-in template directive that makes it easy to iterate over something like an array or an object and create a template for each item.
This post covers Angular 2 and up
Here’s a basic example of its use:
This will output html that looks like this:
- let user creates a local variable that will be available in the template.
- of users means that we’ll be iterating over the users iterable that should be made available in our component.
- The * character before ngFor creates a parent template. It’s a shortcut to the following syntax: template=“ngFor let item of items”.
Available local variables
You can also set local variables for the following exported values: index, first, last, even and odd. index will return the current loop index, and the other values with provide a boolean indicating if the value is true or false. For example:
Will produce the following markup:
Angular NgFor: Everything you need to know
In this tutorial, we are going to learn about the ngFor directive.
Also, we will take a look at the utilities of the ngFor directive, like the index, or even and odd.
When we got the basics, we will move on to some more advanced topics like change-detection and DOM manipulation to tweak the performance of our for-loop using trackBy.
Let's get started!
Displaying multiple elements with ngFor
The so-called ngFor directive is a core directive, that comes with the angular framework itself.
We can use this directive, if we want to display a dynamic list, for example, an array of elements on the screen. This array could look like this example data:
And we want the result to be generated HTML that could look like this:
Using ngFor to render an array
This is exactly what ngFor can do for us.
All we need to do is to tell the directive, which array to use.
Let's say we have a component that we call example-component.
This component has a property that is an array.
That array could be static and look like the array above or could be filled at runtime. For example when data is received from a REST-API.
Now we want to display that array, which sits in the .ts file of the component:
To display that array, we need to use the ngFor directive in our components' template.
How to use the ngFor directive?
The ngFor directive does create the HTML-Element it is placed in as many times as there are elements in the array. So to create a list-element for each array element, we place the ngFor directive inside of the li tag.
The rendered output, give the array above would then look like this:
But that is not exactly what we want right?
We also want to insert the value of each element in between the tags, right?
Working with each element of the list
To do that, we need kind of a reference to each element of the array right?
Fortunately, the angular ngFor directive does provide just that.
Did you notice that the syntax looks like a regular forEach loop? Well, actually it works quite the same way.
With the statement "let element of array" we are defining a variable "element", that holds a reference to the current array element.
Knowing that we can now add the persons' name and the age to each list element. We do so by using the "element" variable we defined inside of the ngFor directive:
Now the output will look just as expected:
It is important to know, that variables defined in the ngFor directive have a scope.
Again, this behavior is quite similar to a regular forEach loop. The defined variable (e.g. "element") is only accessible in the HTML-Element that holds the directive or its children.
For example, this would be valid syntax:
While this is not:
How to get the index of each element
Depending on the use case, only having a reference to each element is not enough.
For example, if we wanted to number each list-element. We would not only require each element, but also its index inside of the array.
To get the index of each element, we can define another variable in the ngFor directive. We can name that variable however we like. Let's call it "i" for now. To get the value of the index, we also need to assign "index" to that variable.
Afterward, we can use "i" inside of the directives' scope, just like the other variables.
The first and the last element of the list
It turns out, the index is not the only value we can get from the ngFor directive.
We can also get the first ("first") or the last ("last") element by assigning its value to a variable, as well. The value of the variable is boolean, depending if the current element is first or last.
This makes sense, if we want to style the first or the last element of the list differently. Using this variables, we can then assign each of them a different class:
If an element is neither the first nor the last element, it does not get assigned any CSS-class.
Using even and odd to increase readability
Another set of values that are available are even and odd.
Just like first and last, this is useful if we want to style elements with an even index differently than those with a odd index. This is commonly used in tables, to increase readability. In that example, every second row has a slightly different color.
Again, we can achieve that effect by assigning CSS-classes depending on the values:
When are changes propagated to the DOM?
Now that we know the basics of ngFor, we are going to take a closer look at how it is working.
One aspect of that, is to know, when changes are applied to the DOM.
Generally, re-rendering of the list occurs in one of three cases:
- When an element is added to the array
- When an element is removed from the array
- When items are reordered
How ngFor is optimizing
To reduce DOM-manipulation to a bare minimum, angulars' ngFor directive is heavily optimized.
For example, if a element is added to the array, it is not re-rendering the whole list. Instead, all the existing DOM-elements are re-used and only the additional element is created.
The same thing happens when a element is removed from the array.
Furthermore, when a element changes its position in the array, angular notices that and only changes the position of the one DOM-element.
To do all that optimization though, angular needs a way to identify each object in the array. Otherwise it cannot determine what happened. By default, it uses the reference of the object for that.
Can we increase the performance of ngFor?
Unfortunately, the default method of identifying objects by reference is quite limited in many cases. Especially in scenarios where a change of the reference cannot be avoided.
For example when working with a REST-API or using immutable data structures, the reference of each object changes all the time.
This would force angular to give up all optimization and re-render the whole list. This is because every reference has changed, so every object looks unfamiliar to angular. Especially with long lists, this can have a big performance impact.
To prevent that behavior, we can help angular with the identification of each object, by providing a so-called trackBy function. With this function, we can tell angular, which properties cause an object to be unique.
In the case of our example, we can use the guid field to identify each object. Because this value does (should) not change when the reference changes, angular can still identify them and apply the optimization.
To specify a trackBy function, we first need to create one in our component. The function gets the index of the element and the element itself. I then have to return the unique value of the element.
In our case this is the guid. But it could also be the hash of the element.
We also need to tell the ngFor directive which function it should use to track the element. This can be done like so:
Hot to use NgFor with Non-Iterables
NgFor does only work with Iterables by design. This is fine, if your data structure is an array, but what about plain objects or maps? Here are some examples of how to use NgFor with different data-structures!
Unfortunately, we can't just use objects with ngFor. But it is not impossible to do. To make objects compatible with ngFor, we need to convert the object to an array. Easy right? But how can we do so in a convenient way?
In my opinion, the best way to do this is in a angular pipe. That way it is convenient to use and also quite efficient.
The pipe to do this looks like this:
This pipe can then be used like this (note that it has to be declared in a module first):
If we deal with observables, like results from the HttpClient, we can use the async pipe, that is provided by the angular framework.
In this tutorial we discovered, how we can use the power of the ngFor directive in our angular application.
I hope you liked this article. If you did, please share it with your friends!
Angular NgFor, <ng-template> - the complete guide
In this post you’re going to learn how to use Angular’s NgFor directive to loop over data to render data or components. Rendering a list of components would be a great use-case for NgFor.
As Angular is a reactive framework, it’s common to see NgFor being used alongside observables, and so our code examples will also follow a reactive style. NgFor does support arrays and array-like objects as well - we’ll explore each approach.
What is NgFor?
NgFor is one of the most commonly used Angular directives that comes with Angular’s CommonModule.
🙌 Tip: Include the in the root module of your app, as it already includes the for us!
NgFor allows us to loop over data and access each and - much like a regular Array ForEach.
The NgFor directive also does far more than just loop and give us a value and index, it can be combined with observables via the pipe or enhance our rendering performance with the function we can provide.
For this article, we’ll be including a further component in our :
Our takes a single of :
So now we’re all setup, what’s next?
Now that our is included in our module, we can setup our to use this dataset:
As mentioned in the introduction, I’m using here from RxJS to give me an Observable stream from the results, this is a nice way to mimic an Observable response, such as when using Angular’s module to return data from an API.
ngFor in practice
Now we’re setup, we can look into our template:
You can see I’m declaring inside of here, as we want to iterate our dataset and populate each contact via the setup inside our .
One way we could do this is using on the component itself, however for simplicity we’ll use the unordered list. Let’s add :
There are a few things happening here, the first you’ll notice a character at the beginning of the , we’ll come onto what this means in the next section when we look at the element. Secondly, we’re creating a context called , using a “for of” loop.
The Directive will clone the and the child nodes. In this case, the is a child node, and a card will be “stamped out” in the DOM for each particular item inside our collection.
🎉 Download it free!
Ready to go beyond ForEach? Get confident with advanced methods - Reduce, Find, Filter, Every, Some and Map.
- 31 pages of deep-dive syntax, real-world examples, tips and tricks
- Write cleaner and better-structured programming logic within 3 hours
✅ Success! Check your email, enjoy.
As an extra bonus, we'll also send you some extra goodies across a few extra emails.
So, now we have available as an individual Object, we can pass the individual into the ``:
If you’re using a static array, or binding the result of an Observable to the template, you can leave the template as it currently is. However, we can optionally bind the Observable directly to the template, which means we’ll need the pipe here to finish things off:
Using trackBy for keys
If you’re coming from an AngularJS background, you’ll have likely seen “track by” when using an , and similarly in React land, using on a collection item.
So what do these do? They associate the objects, or keys, with the particular DOM nodes, so should anything change or need to be re-rendered, the framework can do this much more efficiently. Angular’s defaults to using object identity checking for you, which is fast, but can be faster!
This is where comes into play, let’s add some more code then explain:
Here we’ve added , then given it a value of . This is a function that we’ll add in the component class:
All this function does is use a custom tracking solution for our collection. Instead of using object identity, we’re telling Angular here to use the unique property that each object contains. Optionally, we can use the (which is the index in the collection of each item, i.e. 0, 1, 2, 3, 4).
If your API returns unique data, then using that would be a preferable solution over - as the may be subject to change if you reorder your collection. Using a unique identifier allows Angular to locate that DOM node associated with the object much faster, and it will reuse the component in the DOM should it need to be updated - instead of destroying it and rebuilding it.
Capturing “index” and “count”
The directive doesn’t just stop at iteration, it also provides us a few other niceties. Let’s explore and , two public properties exposed to us on each iteration.
Let’s create another variable called , which we’ll assign the value of to. Angular exposes these values under-the-hood for us, and when we look at the next section with the element, we can see how they are composed.
To log out the index, we can simply interpolate :
This will give us every index, starting from , for each item in our collection. Let’s also expose :
The will return a live collection length, equivalent of . These can optionally be bound and passed into each component, for example you may wish to log out the total length of your collection somewhere, and also pass the of the particular contact into a function :
Accessing first, last, odd, even
Four more properties exposed by (well, actually underneath it uses , a class which generates each context internally). Let’s quickly look at the source code for this:
As I mentioned above, the is what constructs our items, and you can see in the we’ve already taken a look at and ! The last things we need to look at are the getters, which we can explain from the source code above:
- first: returns for the first item in the collection, matches the index with zero
- last: returns for the last item in the collection, matches the index with the total count, minus one to shift the “count” down one to cater for zero-based indexes
- even: returns for even items (e.g. 2, 4) in the collection, uses modulus operator to calculate based off index
- odd: returns for odd items (e.g. 1, 3), simply inverts result
Using this, we can add conditionally apply things such as styling, or hook into the property to know when the collection has finished rendering.
For this quick demo, we’ll use to add some styles to each (note how we create more variables, just like ):
And some styles:
We won’t demonstrate and , as it’s fairly obvious from the above how we can hook those up!
We mentioned earlier in this article that we’d look at understanding what the meant in our templates. This also shares the same syntax as , which you’ve likely also seen before.
So in this next section, we’ll take a deeper dive on , and the element to explain in more detail what’s really happening here.
When using an asterisk () in our templates, we are informing Angular we’re using a structural directive, which is also sugar syntax (a nice short hand) for using the element.
So, what is the element? First, let’s take a step back. We’ll roll back to showing some AngularJS code here, perhaps you’ve done this before or done something similar in another framework/library:
Web Components introduced a new spec a few years ago similar to this idea, called :
Note how we have , which is our “host” Node for the template to be injected into.
You may have seen this term floating around Angular in a few ways, such as prefixes on Nodes (ng-host) or the property in directives.
ngFor and ng-template
First off, is Angular’s own implementation of the tag, allowing us to think about application design in web components and the ideas behind them. It also provides us with more power than the element gives us by default, seamlessly fitting into the way Angular compiles our code.
So how does the above explanation tell us more about and the ? The asterisk is shorthand syntax for using the element.
Let’s start from the basic example:
And demonstrate the equivalent:
That’s a lot different! What’s happening here?
When we use , we’re telling Angular to essentially treat the element the is bound to as a template.
Angular’s element is not a true Web Component (unlike ). It merely mirrors the concepts behind it to allow you to use as it’s intended in the spec. When we compile our code (JiT or AoT), we will see no elements outputted in the DOM. However, this doesn’t mean we can’t use things like Shadow DOM, as they are still completely possible.
Let’s continue, and understand what , and are doing above.
ngFor and embedded view templates
First thing’s first, is a directive! Let’s check some of the source code:
Here, Angular is using attribute selectors as the value of to tell the decorator what attributes to look for.
The directive uses , which implies there are two attributes as a chained selector. So, how does work if we’re not using ?
Angular’s compiler transforms any elements and directives used with a asterisk () into views that are separate from the root component view. This is so each view can be created multiple times.
During the compile phase, it will take and capitalise the , and create a custom key to create .
In our case, Angular will construct a view that creates everything from the tag inwards:
It also creates an invisible view container to contain all instances of the template, acting as a placeholder for content. The view container Angular has created essentially wraps the “views”, in our case this is just inside the tags. This houses all the templates that are created by (one for each row).
A pseudo-output might look like this:
creates an “embedded view” for each row, passing through the view it has created and the context of the row (the index and the row data). This embedded view is then inserted into the view container. When the data changes, it tracks the items to see if they have moved. If they’ve moved, instead of recreating the embedded views, it moves them around to be in the correct position, or destroys them if they no longer exist.
Context and passing variables
The next step is understanding how Angular passes the context to each :
So now we’ve understood and , how does Angular associate with the individual that we then property bind to?
Because has no value, it’s merely an attribute, this is where Angular provides an “implied” value, or as it’s called under-the-hood.
Whilst Angular is creating each item, it uses an class alongside an , and passes these properties in dynamically. Here’s a small snippet from the source code:
Alongside this section of code, we can also see how our aforementioned and properties are kept updated:
You can dig through the directive source code in more detail here.
This is how we can then access the and like this:
Note how we’re supplying and values which are exposed from the instance, unlike .
To learn more techniques, best practices and real-world expert knowledge I’d highly recommend checking out my Angular courses - they will guide you through your journey to mastering Angular to the fullest!
) - so this method can only. Be used with PROVEN partners. To begin with, 2-3 syringes need to be poured into the ass - to cleanse the rectum directly.
You will also like:
- Harmonica keys
- Maplestory bis
- Fortnite toy characters
- Wonderdraft download
- Pixelmon redstone
- 144 berger hybrid
- Paypal sdk
- Dtea stock
- Blue pump box fight code
- Dominus roblox
Weak, weak. All of you women are making up. There are no goats to pass from us, of course.