Angular - 2.26-Generating lists with ngFor.
With all of these instructions learned, let’s now look at the latest integrated directive for now. An important directive though, is that we can click on the add server button but we don’t actually add servers to our list here, right? That list doesn’t grow. It’s totally static. We can change that with ngFor. Let’s see how that works.
In our server component here, we will now manually add our app-server component twice. It would be nicer to have a server array that dynamically adds it. So in the server component here, I’m going to add a new servers property, and it’s a table. And here I could have my test server and my Testserver 2 maybe. And when we swap a new server here, I actually want to access that server array and push a new server on it. And this should of course use the servername I configured.
Now, with this, I have an array of servers. It would now be great if we could replicate the app-server component as often as necessary to have a server for each element of the array. So two up front, and then a new one for every server we add. We can do that. I will get rid of the second application server here and on the first I will place another directive with a star because it is also a structural directive that modifies the dom itself.
This is the ngFor directive. The basic syntax of the ngFor directive looks like this. We define a temporary variable for the inside of a loop by giving it the name you want as a server, for example, and then of Servers. Servers is the property we defined in the TypeScript file and this will now loop through all the elements in this array and assign the individual element to this dynamic server variable. So it’s just like you can know that this loop from a normal JavaScript code, the for loop.
This server variable can now be used in the model but here we don’t really need it to be honest. We will soon learn in the next section how we can transmit data to our own components for them to produce. So for now, we won’t need it. But one thing we should see is that if I save this file and we go back to our application, we always see two because we start with two. But if I add more servers, you see that our list grows and we can click on it as often as we want.
Of course, the content of each server is always static because we cannot pass data like serverName to that component. But this is something we will learn in the next section of the course when we dive deeper into the components and learn how we can create our own properties on the components
We can then define a feature from the outside which would be great to have here. So we’ll look at that in the next section of the course. But before that, let’s practice what we learned in the last videos, and then we’ll also define our course project before delving deeper into the components and data links again.