user2828442
user2828442

Reputation: 2515

Show / hide <ul> on click in Angular

I am trying to show menu on HTML. Currently it is showing all the submenu options. I want it to show the options of the clicked item.

Below is my home.html code

  <ul class="navbar-nav">
    <li data-toggle="dropdown" class="nav-item" *ngFor="let page of list;let i = index" id="id{{page.link_id}}"><span  (click)="showsubmenu(i)">{{page.link_name}}<i class="iconn" *ngIf="page.flg[0].SHOW_ICON=='YES'"><ion-icon name="md-arrow-dropdown"></ion-icon></i></span>

     <ul *ngFor="let sublink of page.sublink; let j=index;"><li >{{sublink.SUBLINK_NAME}}</li></ul>


    </li>
  </ul>

By default the submenu options are coming, see screenshot below:

enter image description here

home.ts code below:

export class HomePage {

 list = [];submenu;
  json_data = [
    {"link_id":"38","link_name":"Contact","flg":[{"SHOW_ICON":"NO"}],"sublink":[]},
    {"link_id":"37","link_name":"Offices","flg":[{"SHOW_ICON":"YES"}],"sublink":[{"SUBLINK_NAME":"test11","SUBLINK_OF":"37","SUBLINK_ID":"10005"}]},
    {"link_id":"34","link_name":"Products","flg":[{"SHOW_ICON":"YES"}],"sublink":[{"SUBLINK_NAME":"Quick Patrol","SUBLINK_OF":"34","SUBLINK_ID":"10004"},{"SUBLINK_NAME":"Link2","SUBLINK_OF":"34","SUBLINK_ID":"10013"}]},
    {"link_id":"33","link_name":"Home","flg":[{"SHOW_ICON":"NO"}],"sublink":[]}
  ];

  constructor(public navCtrl: NavController) {
this.list = this.json_data;
  }


  showsubmenu(index){

    this.submenu= this.list[index]["link_id"];
    console.log(this.submenu);
    this.submenu=this.list[index]["sublink"];
    console.log(this.submenu.length);

  }
}

Upvotes: 2

Views: 3201

Answers (2)

Vega
Vega

Reputation: 28711

Introduce a new property which will keep the opened menu index. With ngIf toggle show/hide the submenu:

HTML:

//First li
<li (click)="show === i ? show =- 1: show = i" ....>

//second li
<li *ngIf="show === i">....

Typescript:

...
show = -1;
...

DEMO

Upvotes: 4

Srikanth Sharma
Srikanth Sharma

Reputation: 2037

<ng-container *ngIf="page.flg[0]=='NO'?null:true"><ul *ngFor="let sublink of page.sublink; let j=index;"><li >{{sublink.SUBLINK_NAME}}</li></ul></ng-container>

in *.ts, you can add

showsubmenu(index) { this.list[index]['flg'][0] === 'NO'? 'YES' : 'NO'; }

it would be better if you keep 'flg' key as boolean instead of an Array of string. And instead of 'showsubmenu()', you can handle the flg key value in html itself like:

(click)="page.flg?null:true"

Upvotes: 0

Related Questions