Iterating over array/JSON in Typescript to build Angular 2 template menu with submenus

update: Plunker session added on request. (no experience so will likely need help getting it to run on Plunker)

Building up a menu system using Node, Angular 2 and Typescript. Creating the output with manually added content works just fine, but having trouble wanting to mod this to iterate over a more complex array to create menu and sub-menu items. I see examples of for(var a in array) and for(var a of array), but perplexed as to which is the best way to go. Here is the current setup:

my menu.component.ts:

import {Component} from 'angular2/core';

export class MenuContent {
  constructor (
    public id: number,
    public name: string
  ) { }

  selector: 'jimmmenu',
  templateUrl: 'app/menu.html'

export class MenuComponent {
  menuTitle = 'Menu!';

  menuContent = [
    new MenuContent(1, 'menu item'),
    new MenuContent(2, 'menu item'),
    new MenuContent(3, 'menu item'),
    new MenuContent(4, 'menu item')

  Menu = this.menuContent[0];


the menu.html template:

        <li *ngFor="#menu of menuContent">{{}} {{}}</li>

and the index.ejs snippet where the menu is placed:

    <script src='/'></script>

As I said, everything works fine like this, producing a simple list of menu items. But when I try to do something like:

menuData = {
    "menu": [
      { "id": 0, "name": "DasnBoard", "image":"/Images/dashboard_on.gif", "link": "page0.html", 
        "subMenu": [
          { "id": 10, "name": "Main", "image": null, "link": "page1.html", "subMenu": null },
          { "id": 11, "name": "ET & Moisture", "image": null, "link": "page2.html", "subMenu": null }

for(var m in menuData) {
    menuContent = [ new MenuContent([m].id,[m].name); ]

…things start going awry, such as the Chrome Inspector crying ‘Uncaught SyntaxError: Unexpected token ;‘ on the line with the for(). And yes I know that the loop would only add the last one… it’s a bad example, for sure.

Essentially I’m trying to do the following, but looping through the menuData array instead of populating menuContent by hand with long drawn-out menu/submenu assignments:

menuContent = [
  new MenuContent([0].id,[0].name),
  new MenuContent([0].subMenu[0].id,[0].subMenu[0].name),

Admittedly my Typescript and Angular 2 knowledge is small and the available google-results seems sparse on similar ideas, which is why I turn to you all for assistance or prodding in the right direction. Appreciate any insights.

Leave a Reply

1 Comment threads
0 Thread replies
Most reacted comment
Hottest comment thread
1 Comment authors
Jason Recent comment authors
newest oldest most voted
Notify of

You could use this approach for simplicity:

<ul class="menu">
<li *ngFor="#item of items">
    <ul class="sub-menu">
        <li *ngFor="#subitem of item.subMenu">