⚠️ This lesson is retired and might contain outdated information.

Build Dynamic Angular Navigation with ngFor

John Lindquist
InstructorJohn Lindquist
Share this video with your friends

Social Share Links

Send Tweet
Published 8 years ago
Updated 9 months ago

It’s often easier to build out your navigation dynamically so that you have programmatic control of which navigation elements appear (and those which don’t). You can leverage the power of Angular’s *ngFor directive to build out navigation based on any set of data you provide with urls.

[00:00] Now this nav has gotten very repetitive, so it looks like something that would be a candidate for NgFor, because on an a tag, I can just say NgFor, then create some nav variables. We'll say nav of navs. Then set up a navs array inside of our app components.

[00:17] Navs is an array, and these little objects will be our nav objects. We'll have a URL, and content of home, then just make a couple more of these. A URL of contacts, content, contacts, and a URL of contacts/one, content, let's say, one.

[00:40] With these navs, we now have an NgFor-led nav of navs. We'll loop in through these. We can go ahead and take this home, and call this nav.content. Hit save, and you'll see each of these change. The home, contacts, and one, just like we have home, contacts, and one.

[00:58] In our router link, this now has to be nav.url. Let's see what happens now is that if I had to click on home, this would try and take me to nav.url, and you'll see an error show up saying, "Cannot match any routes, nav.url."

[01:13] That's because it's evaluating this as a string. We have to make sure that this is an object that needs to be valuated, and get the string off of that .url. Always remember to use the square brackets around an attribute where you need the right side to be evaluated.

[01:29] You never use the curly braces in here. You use the brackets on the left side. Now these will be evaluated properly so that when I click on home, I go home. When I click on contacts, I go to contacts. When I click on one, I go to one, because nav.url matches no path, the path of contacts, and the path of contacts/one.