Home > Net >  Why my loop, loop twice in Angular/TypeScript?
Why my loop, loop twice in Angular/TypeScript?

Time:12-04

To keep it simple, I created a menu and all of my bullet lists are stored in an array.

My problem is that when I run the loop it shows me 2 times, the same values ?? I do not understand why?

enter image description here

I think that the problem is in the HTML file?

admin.component.html

<div >
  <div >
    <i ></i>
    <span >Menu</span>
  </div>
  <ul  *ngFor="let menu of menus; let i = index">
    <li>
      <a routerLink="market">
        <i ></i>
        <span > {{ menu.item }} </span>
      </a>
    </li>

    <li>
      <a routerLink="portfolio">
        <i ></i>
        <span >{{ menu.item }} </span>
      </a>
    </li>
  </ul>
</div>
<section >
  <nav>
    <div >
      <i ></i>
      <span >Dashboard</span>
    </div>
  </nav>
  <router-outlet></router-outlet>
</section>

TS

export class AdminComponent implements OnInit {
  showSubmenu: any[] = [];

  menus: any[] = [
    {
      item: 'Market',
      submenus: [{ item: 'Item' }],
    },
    {
      item: 'Portfolio',
      submenus: [{ item: 'Element' }],
    },
  ];

  constructor() {}

  ngOnInit() {}

  toggleMenu(index: number) {
    this.showSubmenu[index] = !this.showSubmenu[index];
  }
}

I can not retrieve the index of each array? I can do this? If so... How, please?

https://stackblitz.com/edit/angular-ivy-9ytvbk?file=src/app/admin/admin.component.html

CodePudding user response:

Please look at this solution :

https://stackblitz.com/edit/angular-ivy-1hnhqr?file=src/app/admin/admin.component.html

  • Related