Search code examples
angularangular2-directivesngforangular-ng-if

Understanding *ngFor from Angular 2


I'm trying to use a nested *ngFor in my Angular project to render a dynamic menu. I'm trying something like this:

<li class="treeview" *ngFor="let pm of parentMenu">

    <a href="#">
      <i class="fa fa-edit"></i> <span>{{pm.MenuTitle}}</span>
      <span class="pull-right-container">
        <i class="fa fa-angle-left pull-right"></i>
      </span>
    </a>
    <ul class="treeview-menu" *ngFor="let cm of childMenu">
      <li *ngIf="cm.ParentMenuId == pm.Id">{{cm.MenuTitle}}</li>
    </ul>
  </li>

I'm only getting the first element of childMenu, my understanding was *ngFor works similar to foreach in C#, but clearly, that's not the case. Could someone please help me fix the code and understand it?


Solution

  • You are correct that ngFor behaves like a foreach or for loop.

    I suspect your problem is the object you are binding to.

    using basically your code there should be a property on the component called parentItem that is an array with nested properties including childMenu

    parentMenu = {
        'Parent1':[{'menuTitle':'Menu 1', 'childItem':[
          {'menuTitle':'sub item 1'}]
          },
         {'menuTitle':'A cool menu', 'childItem':[
           {'menuTitle':'sub item 1'},
         {'menuTitle': 'sub item 2'}]
         }]
      }
    

    and then your HTML should work much like:

    <li class="treeview" *ngFor="let pm of parentMenu.Parent1">
    
        <a href="#">
          <i class="fa fa-edit"></i> <span>{{pm.menuTitle}}</span>
          <span class="pull-right-container">
            <i class="fa fa-angle-left pull-right"></i>
          </span>
        </a>
        <ul class="treeview-menu" *ngFor="let cm of pm.childItem">
          <li>{{cm.menuTitle}}</li>
        </ul>
      </li>
    

    And for reference in action a working stackblitz from your code: