Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson

Already subscribed? Sign In

Autoplay

    Build Dynamic Angular Navigation with ngFor

    John LindquistJohn Lindquist

    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.

    angularAngular
    2 - 4
    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Transcript

    Transcript

    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.

    Discuss

    Discuss