Angular 8/7 + ng-bootstrap | Accordion Tutorial by Example

In this tutorial, we will discuss how to add Bootstrap Accordion in Angular Project using ng-bootstrap package with multiple option properties.

We will create a new Angular project then install the ng-bootstrap package to use its UI components like Accordion.

let’s get started!

Create an Angular Project

First, we will create a new Angular project using Ng CLI tool in the latest version 8.3.3.

Run the following command in teminal to create a new Angular project:

$ ng new ng-bootstrap-accordion-demo

Install Bootstrap in Angular Project

Let's install Bootstrap by running following NPM command. This will install the latest bootstrap version ( Current is 4.3.1 )

$ npm install --save @ng-bootstrap/ng-bootstrap

ng-bootstrap includes UI components only, so for adding styling to these components we need to include CSS styling file in the index.html at Angular project root

  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" >

 

Import NgbModule ( Bootstrap module ) & FormsModule ( for Angular as we will use [(ngModel)] ) in the app.module.ts file

// app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';

import { NgbModule } from '@ng-bootstrap/ng-bootstrap';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    NgbModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Add Bootstrap Accordion

To use the Accordion component we use ngb-accordion which acts as a wrapper for Accordion panels which are added by using ngb-panel as shown below:

<ngb-accordion>
	<ngb-panel title="Panel One">
		<ng-template ngbPanelContent>
			Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia
			aute.
		</ng-template>
	</ngb-panel>
	<ngb-panel title="Panel Two">
		<ng-template ngbPanelContent>
			Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia
			aute.
		</ng-template>
	</ngb-panel>
	<ngb-panel title="Panel Three">
		<ng-template ngbPanelContent>
			Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia
			aute.
		</ng-template>
	</ngb-panel>
</ngb-accordion>

Each panel is created using ngb-panel directive with title property. Content of each panel is provided by ngbPanelContent directive used with ng-template.

Now let's discuss some important properties:

NgbAccordion

The ngb-accordion components act as a wrapper for accordion panels. It takes the following input and output properties:

Input Properties:

activeIds: Takes an array or comma-separated string if panel ids which we want to open initially.

closeOthers: It enables the accordion to open only one panel at a time. Default is set to true.

destroyOnHide: When the panel is closed/ collapsed, it is removed from DOM. Default is set to true.

type: Used to add style to panels from the following types:'success', 'info', 'warning', 'danger', 'primary', 'secondary', 'light' and 'dark'.

Output Properties:

panelChange: This event is emitted before panel toggle.

Methods:

Following methods can be used to control Accordion component:

isExpanded: Check if panel with provided Id is expanded.

expand: Expands a panel with a provided id.

expandAll: Expands all panels.

collapse: Collapses a panel with the provided id.

collapseAll: Collapses all panels.

toggle: Toggles a panel with the provided id.

<ngb-accordion 
    #myaccordion="ngbAccordion" 
    activeIds="panelTwo" 
    closeOthers="true" 
    type="'success'"
    (panelChange)="beforeChange($event)">
    <ngb-panel title="Panel One" id="panelOne">
        <ng-template ngbPanelContent>
            Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon
            officia
            aute.
        </ng-template>
    </ngb-panel>
    <ngb-panel title="Panel Two" id="panelTwo">
        <ng-template ngbPanelContent>
            Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon
            officia
            aute.
        </ng-template>
    </ngb-panel>
    <ngb-panel title="Panel Three" id="panelThree">
        <ng-template ngbPanelContent>
            Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon
            officia
            aute.
        </ng-template>
    </ngb-panel>
</ngb-accordion>

<button class="btn btn-sm btn-outline-primary mr-2" (click)="togglePanel('panelOne')">Toggle Panel One</button>
<button class="btn btn-sm btn-outline-primary mr-2" (click)="togglePanel('panelTwo')">Toggle Panel Two</button>

In component import NgbPanelChangeEvent & NgbAccordion to use output properties and method events using a template reference variable #myaccordion.

// accordion.component.ts
import { Component, OnInit, ViewChild } from '@angular/core';
import { NgbPanelChangeEvent, NgbAccordion } from '@ng-bootstrap/ng-bootstrap';

@Component({
  selector: 'app-accordion',
  templateUrl: './accordion.component.html',
  styleUrls: ['./accordion.component.css']
})
export class AccordionComponent implements OnInit {


  @ViewChild('myaccordion', {static : true}) accordion: NgbAccordion;

  constructor() { }

  ngOnInit() {
  }

  beforeChange($event: NgbPanelChangeEvent) {
    console.log($event.panelId);
    if ($event.panelId === 'panelOne') {
      $event.preventDefault();
    }

    if ($event.panelId === 'panelTwo' && $event.nextState === false) {
      $event.preventDefault();
    }
  }

  togglePanel(id){
    this.accordion.toggle(id);
  }


}

NgbPanel

This directive is used to create a panel in accordion.

It takes the following properties:

Input Properties:

disabled: If true the panel is disabled.

id: Provides an identifier to the accordion panel. Otherwise auto-generated in format ngb-panel-xxx

title: Defines the title of the panel.

type: Type of panel from the following:'success', 'info', 'warning', 'danger', 'primary', 'secondary', 'light' and 'dark'.

....
....
    <ngb-panel 
        title="Panel One" 
        id="panelOne"
        disabled="true"
        >
        <ng-template ngbPanelContent>
            Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon
            officia
            aute.
        </ng-template>
    </ngb-panel>
....
....

NgbPanelContent

This directive wraps the accordion panel content with ng-template to have any HTML markup.

....
....
    <ngb-panel title="Panel Two" id="panelTwo">
        <ng-template ngbPanelContent>
            Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon
            officia
            aute.
        </ng-template>
    </ngb-panel>
....
....

NgbPanelHeader

Panel header can be customized with HTML markup using ngbPanelHeader directive with ng-template as shown below:

<ngb-accordion #a="ngbAccordion" activeIds="custom-panel-1">
    <ngb-panel id="custom-panel-1">
        <ng-template ngbPanelHeader let-opened="opened">
            <div class="d-flex align-items-center justify-content-between">
                <h5 class="m-0">First panel - {{ opened ? 'opened' : 'collapsed' }}</h5>
                <button ngbPanelToggle class="btn btn-link p-0">Toggle first</button>
            </div>
        </ng-template>
        <ng-template ngbPanelContent>
            Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon
            officia
        </ng-template>
    </ngb-panel>
</ngb-accordion>

Above we also used NgbPanelToggle which is used inside NgbPanelHeader to toggle current pannel

NgbPanelTitle

The directive that wraps only the panel title to have custom HTML markup inside as shown below:

...
...   
 <ngb-panel id="panelTwo">
        <ng-template ngbPanelTitle>
            <span>&#9733; <b>Panel</b> Two &#9733;</span>
        </ng-template>
        <ng-template ngbPanelContent>
            Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon
            officia
            aute.
        </ng-template>
    </ngb-panel>
...
...

 

Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments