Tuesday, 11 April 2017

Collapsible menu using Angular 2 | Nested menu using Angular 2

Here I am going to explain about how to implement a simple collapsible or nested menu using Angular 2. Let us create a simple component first.

Component


@Component({
  selector: 'my-app',
  template: `./app.component.html`,
  styleUrls : ['style.css']
})
export class App {
  title:String;
  menuList:any;
  constructor() {
    this.title = "Collapsible menu - Angular 2";
 this.menuList = [
  {
   "name": "Angular",
   "subMenu": ["Anguler 1", "Angular 2"]
 },
 {
  "name": "Javascript",
  "subMenu": ["Jquery", "Ajax"]
 },
 {
  "name": "Bootstrap",
  "subMenu": ["BootStrap 2", "BootStrap 3"]
 }
 ]
  }
}

Html


<div>
<h4>{{title}}</h4>
<ul>
 <li *ngFor="let n of menuList"><span>{{n.name}}</span>
  <ul>
   <li *ngFor="let child of n.subMenu">{{child}}</li>
  </ul>
 </li> 
</ul>
</div>

We are done with our simple nested loop. Now we need to implement a collapsible logic using angular 2. Let's modify the code to do that.

Updated html


<div>
<h4>{{title}}</h4>
<ul>
 <li *ngFor="let n of menuList" (click)="select(n.name);" 
[ngClass]="{active: isActive(n.name)}"><span>{{n.name}}</span>
  <ul style="display:none;">
   <li *ngFor="let child of n.subMenu">{{child}}</li>
  </ul>
 </li> 
</ul>
</div>

Here I have used angular 2 click method and angular ngFor to loop the array.

Updated component


@Component({
  selector: 'my-app',
  template: `./app.component.html`,
  styleUrls : ['style.css']
})
export class App {
  title:String;
  menuList:any;
  selected:any;
  constructor() {
    this.title = "Collapsible menu - Angular 2";
 this.menuList = [
  {
   "name": "Angular",
   "subMenu": ["Anguler 1", "Angular 2"]
 },
 {
  "name": "Javascript",
  "subMenu": ["Jquery", "Ajax"]
 },
 {
  "name": "Bootstrap",
  "subMenu": ["BootStrap 2", "BootStrap 3"]
 }
 ]
  }
  select(item){
     this.selected = (this.selected === item ? null : item);
  }
  isActive(item){
    return this.selected === item;
  }
}

And don’t forgot to add these css

CSS


ul li{cursor:pointer;}
.active{
  color:blue;
}
.active ul{
  display:block !important;
}

We are done. Click on the menu item and you can see the collapsible effect.

Related Post

1. Get selected values on click and show in the UI - Angular js 2

2. Simple search using pipe in angular 2

3. Date filtering and formatting using pipe in Angular 2

4. Select all/ deselect all checkbox - Angular 2

No comments :

Post a Comment