Angular 2 Accordion expand only one at a time

angular 2 accordion example angular 2 material accordion angular 2 accordion plunker angular 2 accordion animation angular 2 accordion component without ng2-bootstrap accordion without ng2-accordion example

Createing accordion demo in Angular 2 is more than easy, Angular have rich of conditional features which we will see in this article, like how to apply more than one class on the basis of some conditional values. For this demo we are not goign to write some fancy CSS and animation but use the hard coded data and use ngFor loop and index to create dynamically our list of items in accordion and show the only active item detail.

Just copied some title and description from "Lorem Ipsum" web site and created an array of items like this

[
    {
        "title": "What is Lorem Ipsum?",
        "description": "Lorem Ipsum is ....."
    },
    {
        "title": "Why do we use it?",
        "description": "It is a long established fact that a reader...."
    }   
]

Let's create our component, give whatever the name you like, say app.component.ts and add following code

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'demo-app',
  templateUrl: 'app/app.component.html'
})
export class AppComponent implements OnInit  {

  current: number = 0;
  items: Array<any>;  

  constructor() {}

  ngOnInit(){    
    this.items =    [
        {
            "title": "What is Lorem Ipsum?",
            "description": "Lorem Ipsum is ....."
        },
        {
            "title": "Why do we use it?",
            "description": "It is a long established fact that a reader...."
        }   
    ]       
  }   
}

There is nothing special which need to explain, only to variables, current and items, current will hold the currently selected item inxed, default to zero(0) and items will hold our hard coded items.

Create a HTML file for our template give any name, if you note in our component we used app.component.html as templateUrl. For design and look & feel we will use bootstrap.

Here is the complete HTML of the page, look at the code closely, we are going to looke line be line:

<div id="panel-group">
  <div class="panel panel-default" *ngFor="let item of items; let i = index">
    <div class="panel-heading" (click) = "current = i">
       <h5 class="panel-title">
          <i class='glyphicon' 
            [class.glyphicon-chevron-right] = "i != current"
            [class.glyphicon-chevron-down] = "i == current" ></i>   {{item.title}}
       </h5>
    </div>
     <div id="collapse1" class="panel-collapse" [class.collapse]='current != i'>
      <div class="panel-body">{{item.description}}</div>
    </div>
  </div>
</div>

We know the ngFor loop so don't need to explain, in the same line we use let i = index, it is used to copy the loop index to a variable i.

Next line div class panel-heading have a click event which copy the i to current variable so we can expand it and close rest of the items. Let's say you click on the 3rd row then i woud be 2 so copied to current.

We used i element of HTML to show the direction icons and it have normal class = 'glyphicon' of bootstrap, because it is common in all cases. Let's take this code out and explain how it apply different classes:

<h5 class="panel-title">
  <i class='glyphicon' 
    [class.glyphicon-chevron-right] = "i != current"
    [class.glyphicon-chevron-down]  = "i == current" ></i> {{item.title}}
</h5>

if value of current variable is equal to index, it will apply class 'glyphicon-chevron-down' and if not then 'glyphicon-chevron-right'.

Same trick we used to show hide the body content, to hide we apply collapse class. If current variable value is not equal to index then apply collapse class, see the body html

<div id="collapse1" class="panel-collapse" [class.collapse]='current != i'>
    <div class="panel-body">{{item.description}}</div>
</div>

That's it.

Ali Adravi Having 13+ years of experience in Microsoft Technologies (C#, ASP.Net, MVC and SQL Server). Worked with Metaoption LLC, for more than 9 years and still with the same company. Always ready to learn new technologies and tricks.
  • angular2
  • angularjs
  • accordion
  • bootstrap
By Ali Adravi On 19 May, 17  Viewed: 1,615

Other blogs you may like

Angular 2 CRUD with Web API 2

Angular 2 insert update, delete, search, sort feature we will try in this article which we will improve with dynamic component loading and image upload with drag and drop feature in coming articles with the same base code. We are going to use Angular-CLI 4 for this application. What we need to... By Ali Adravi   On 03 Sep 2017  Viewed: 172

Angular 2 Dynamically Add & remove Components

Angular 2 gives full control to add or remove component in other component programmatically by simple steps. In this article we are going to see how to add, remove experience component to any other component, we will also try to pass some values to component from parent to child component to see if... By Ali Adravi   On 27 Aug 2017  Viewed: 262

Angular 2 Page Title Static and Dynamic with built-in Title Service

Angular 2 have a built-in service called Title, while in angularjs or angular 1 we were maintaining it through the routing or through the service. By using the Title service provided by Angular 2, in 2 minute every thing will be set without any complication, even we don't need to understand the... By Ali Adravi   On 14 Apr 2017  Viewed: 1,174

Angularjs CRUD with Web API, Entity Framework & Bootstrap modal popup part 2

Add/Edid Customer in Modal Popup --- In previous article we discussed how to search, delete and show detail of customer and contact list. In this article we will try to open the modal popup to add new customer and edit an existing customer record. I divided article in two parts because of the... By Ali Adravi   On 29 Jul 2015  Viewed: 14,128

Custom Directives in AngularJS with example and demo

Angularjs custom directives are the common to avoid the duplicate code, it is easy powerful and really nice. There are already too many directive have been created by experts but as a developer we need to write our own to achieve our specific goal. ng-model, ng-if, ng-show, ng-repeat all these are... By Ali Adravi   On 29 Jul 2015  Viewed: 2,842