
Syncfusion Angular Accordion
- 150 installs
- Updated August 4, 2026
- syncfusion/angular-ui-components-skills
Helps with ai & agent building tasks.
About
syncfusion-angular-accordion is a Claude Code skill for ai & agent building. It helps solo builders move faster with AI-assisted development.
- syncfusion-angular-accordion
- AI & Agent Building
- AI-coding skill
Syncfusion Angular Accordion by the numbers
- 150 all-time installs (skills.sh)
- +5 installs in the week ending Jul 27, 2026 (Skillselion tracking)
- Ranked #3,337 of 16,546 AI & Agent Building skills by installs in the Skillselion catalog
- Data as of Aug 5, 2026 (Skillselion catalog sync)
npx skills add https://github.com/syncfusion/angular-ui-components-skills --skill syncfusion-angular-accordionAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 150 |
|---|---|
| Last updated | August 4, 2026 |
| Repository | syncfusion/angular-ui-components-skills ↗ |
What it does
Helps with ai & agent building tasks.
Files
Implementing Syncfusion Angular Accordion Component
When to Use This Skill
Use this skill when you need to:
- Create collapsible content panels - Organize related content into expandable sections that collapse to save space
- Build step-by-step wizards - Create multi-step forms or workflows where users progress through accordion items
- Implement FAQ sections - Display frequently asked questions with expandable answers
- Create navigation menus - Build hierarchical menus or navigation structures with nested expandable items
- Load content dynamically - Fetch and display content on-demand as users expand accordion items
- Add custom animations - Enhance user experience with smooth expand/collapse transitions
- Organize complex data - Display structured data with expandable categories and subcategories
Component Overview
The Syncfusion Angular Accordion component displays a vertically collapsible content panel where users can expand one or more sections at a time. Key capabilities include:
- Single/Multiple expand modes - Control whether one or multiple items can be open simultaneously
- Data binding - Bind accordion items from arrays or OData services
- Dynamic item management - Add, remove, or update items at runtime
- Event handling - Respond to expand, collapse, and click events
- Custom animations - Configure smooth transitions with custom effects and duration
- Nested accordions - Create hierarchical accordion structures for complex navigation
- TreeView integration - Embed other components like TreeView for advanced navigation
- Content projection - Use Angular's
ng-contentfor reusable content components
Master Table of Contents
Quick Navigation to Documentation: 1. Getting Started - Installation, setup, and basic initialization 2. Expand Modes - Single vs. Multiple expand modes, configuration 3. Data Binding - Data sources, OData, REST APIs, refresh strategies 4. Dynamic Loading and Interactions - Events, methods, dynamic item management 5. Advanced Features - Animations, nested accordions, styling, RTL 6. Use Cases and Patterns - Real-world implementations and patterns
Documentation and Navigation Guide
Getting Started
📄 Read: references/getting-started.md
When to use:
- Setting up your first Accordion component
- Installing required packages and dependencies
- Understanding CSS imports and theme configuration
- Learning basic initialization methods (template-based, items array, HTML elements)
- Creating your first working example
Expand Modes
📄 Read: references/expand-modes.md
When to use:
- Deciding whether users should expand one or multiple items
- Configuring single mode (only one item open at a time)
- Using multiple mode for simultaneously open items
- Selecting the right mode for your use case
- Handling performance with large datasets
Data Binding
📄 Read: references/data-binding.md
When to use:
- Binding accordion data from external sources
- Using DataManager to fetch from OData services
- Mapping data properties to headers and content
- Working with structured data arrays
- Refreshing accordion content after data updates
Dynamic Loading and Interactions
📄 Read: references/dynamic-loading-and-interactions.md
When to use:
- Adding items dynamically at runtime
- Handling expand/collapse/click events
- Loading content via AJAX or remote requests
- Implementing checkbox-controlled expansion
- Preventing item collapse or forcing items to stay open
- Using
ng-contentfor reusable content components - Creating always-open accordion items
Advanced Features
📄 Read: references/advanced-features.md
When to use:
- Customizing expand/collapse animations with effects and easing
- Creating nested accordions for hierarchical structures
- Integrating TreeView components within accordion items
- Applying custom CSS styling and theming
- Enabling RTL (right-to-left) support
- Styling headers, items, and expand/collapse icons
Use Cases and Patterns
📄 Read: references/use-cases-patterns.md
When to use:
- Building FAQ sections with best practices
- Creating multi-step wizard forms with validation
- Designing settings panels with categories
- Building navigation menus and organizational hierarchies
- Displaying help and documentation sections
- Learning real-world patterns and code organization strategies
Quick Start Example
Basic template-based accordion with three items:
import { Component } from '@angular/core';
import { AccordionModule } from '@syncfusion/ej2-angular-navigations';
@Component({
standalone: true,
selector: 'app-root',
imports: [AccordionModule],
template: `
<ejs-accordion>
<e-accordionitems>
<e-accordionitem expanded="true">
<ng-template #header>
<div>ASP.NET</div>
</ng-template>
<ng-template #content>
<div>Microsoft ASP.NET is a set of technologies in the Microsoft .NET Framework for building Web applications and XML Web services.</div>
</ng-template>
</e-accordionitem>
<e-accordionitem>
<ng-template #header>
<div>ASP.NET MVC</div>
</ng-template>
<ng-template #content>
<div>The Model-View-Controller (MVC) architectural pattern separates an application into three main components: the model, the view, and the controller.</div>
</ng-template>
</e-accordionitem>
<e-accordionitem>
<ng-template #header>
<div>JavaScript</div>
</ng-template>
<ng-template #content>
<div>JavaScript (JS) is an interpreted computer programming language used for creating interactive web pages and applications.</div>
</ng-template>
</e-accordionitem>
</e-accordionitems>
</ejs-accordion>
`
})
export class AppComponent {}Using items array approach:
import { Component } from '@angular/core';
import { AccordionModule } from '@syncfusion/ej2-angular-navigations';
@Component({
standalone: true,
selector: 'app-root',
imports: [AccordionModule],
template: `<ejs-accordion [items]="accordionItems"></ejs-accordion>`
})
export class AppComponent {
public accordionItems = [
{
header: 'ASP.NET',
content: 'Microsoft ASP.NET is a set of technologies in the Microsoft .NET Framework for building Web applications.',
expanded: true
},
{
header: 'ASP.NET MVC',
content: 'The Model-View-Controller (MVC) architectural pattern separates an application into three main components.'
},
{
header: 'JavaScript',
content: 'JavaScript (JS) is an interpreted computer programming language used for creating interactive web pages.'
}
];
}Common Patterns
Pattern 1: Single Expand Mode (One Item Open)
Use when you want only one accordion item open at a time, common for navigation menus and settings panels.
<ejs-accordion expandMode="Single">
<!-- items here -->
</ejs-accordion>Pattern 2: Dynamic Item Addition
Add items programmatically in response to user actions or data loading.
@ViewChild('accordion') accordionObj?: AccordionComponent;
addNewItem() {
this.accordionObj?.addItem({
header: 'New Item',
content: 'New content here'
});
}Pattern 3: Event-Driven Workflows
Respond to accordion events for custom logic like validation or data loading.
<ejs-accordion (expanding)="onExpanding($event)" (expanded)="onExpanded($event)">
<!-- items here -->
</ejs-accordion>
onExpanding(event: ExpandEventArgs) {
// Prevent collapse of currently open item
event.cancel = true;
}Pattern 4: Animated Expand/Collapse
Add smooth animations for better visual feedback.
<ejs-accordion [animation]="animationSettings">
<!-- items here -->
</ejs-accordion>
animationSettings = {
expand: { effect: 'SlideDown', duration: 400, easing: 'ease' },
collapse: { effect: 'SlideUp', duration: 400, easing: 'ease' }
};Complete API Reference
For detailed documentation on each API element with working code examples, refer to the reference files. Below is a comprehensive summary.
Accordion Component Properties (13 Total)
| Property | Type | Default | Purpose | Learn More |
|---|---|---|---|---|
items | AccordionItemModel[] | [] | Collection of accordion items | Data Binding |
dataSource | `DataManager \ | Object[]` | null | Data source for binding items |
expandMode | `'Single' \ | 'Multiple'` | 'Multiple' | Controls single or multiple item expansion |
expandedIndices | number[] | [] | Indices of initially expanded items | Expand Modes |
animation | AccordionAnimationSettingsModel | { expand: { effect: 'SlideDown', duration: 400, easing: 'linear' }, collapse: { effect: 'SlideUp', duration: 400, easing: 'linear' } } | Expand/collapse animation settings | Advanced Features |
headerTemplate | `string \ | Function` | null | Template for item headers |
itemTemplate | `string \ | Function` | null | Template for item content |
height | `string \ | number` | auto | Component height |
width | `string \ | number` | 100% | Component width |
enableRtl | boolean | false | Enable right-to-left layout | Advanced Features |
enablePersistence | boolean | false | Save expanded state in localStorage | Getting Started |
enableHtmlSanitizer | boolean | true | Sanitize HTML in content | Data Binding |
locale | string | 'en-US' | Localization culture | Advanced Features |
AccordionItem Properties (8 Total)
| Property | Type | Default | Purpose | Learn More |
|---|---|---|---|---|
header | `string \ | HTMLElement` | '' | Item header text or element |
content | `string \ | HTMLElement \ | Function` | '' |
expanded | boolean | false | Initial expanded state | Expand Modes |
disabled | boolean | false | Disable item interaction | Dynamic Loading |
visible | boolean | true | Item visibility | Dynamic Loading |
cssClass | string | '' | Custom CSS class for item | Advanced Features |
iconCss | string | '' | Font Awesome/Bootstrap icon class | Getting Started |
id | string | '' | Unique item identifier | Getting Started |
Methods (7 Total)
| Method | Signature | Purpose | Learn More |
|---|---|---|---|
addItem() | `addItem(item: AccordionItemModel \ | Object[], index?: number): void` | Add items at specific index or end |
removeItem() | removeItem(index: number): void | Remove item at index | Dynamic Loading |
expandItem() | expandItem(isExpand: boolean, index?: number): void | Expand/collapse specific or all items | Dynamic Loading, Expand Modes |
enableItem() | enableItem(index: number, isEnable: boolean): void | Enable/disable item interaction | Dynamic Loading |
hideItem() | hideItem(index: number, isHidden?: boolean): void | Show/hide item without removal | Dynamic Loading |
select() | select(index: number): void | Set focus to item header | Dynamic Loading |
destroy() | destroy(): void | Clean up component resources | Dynamic Loading |
Events (5 Total)
| Event | Event Args | Triggered When | Learn More |
|---|---|---|---|
created | Event | Component rendering completes | Dynamic Loading |
expanding | ExpandEventArgs | Item begins to expand (cancellable) | Dynamic Loading |
expanded | ExpandEventArgs | Item finishes expanding | Dynamic Loading |
clicked | AccordionClickArgs | Header or content clicked | Dynamic Loading |
destroyed | Event | Component destroyed | Dynamic Loading |
Animation Effects (6 Types)
| Effect | Expand Behavior | Collapse Behavior | Best For |
|---|---|---|---|
SlideDown | Content slides down | N/A (use with SlideUp) | Default, smooth animations |
SlideUp | N/A (use with SlideDown) | Content slides up | Default collapse effect |
FadeDown | Content fades in while sliding | N/A (use with FadeUp) | Professional appearance |
FadeUp | N/A (use with FadeDown) | Content fades out while sliding | Professional appearance |
Zoom | Content zooms in | Content zooms out | Attention-grabbing effects |
None | Instant | Instant | Best performance |
Easing Functions (5 Types)
| Easing | Curve | Best For | Typical Use |
|---|---|---|---|
linear | Constant speed | Simple animations | Straightforward expand/collapse |
ease | Slow start/end, fast middle | Default behavior | Balanced feel |
ease-in | Accelerating | Collapse action | Speeds up as it closes |
ease-out | Decelerating | Expand action | Slows down as it opens |
ease-in-out | Slow start and end | Symmetric animations | Equal timing both directions |
Common Use Cases
1. FAQ Section - Expandable question/answer pairs with single expand mode 2. Multi-Step Wizard - Sequential items with validation and conditional enabling 3. Settings Panel - Grouped settings organized in expandable sections 4. Navigation Menu - Hierarchical navigation with nested accordions 5. Data Explorer - Expandable data categories with dynamic loading 6. Help Documentation - Collapsible help sections organized by topic
Troubleshooting Quick Reference
Item won't expand?
- Check if item is disabled with
enableItem(false, index) - Verify
expandModesetting matches your requirement
Content not loading?
- Ensure
headerandcontentproperties are set - Check CSS imports are included in styles
Animation not smooth?
- Verify CSS is properly imported
- Check browser console for errors
- Consider reducing animation duration for slower devices
Multiple items closing unexpectedly?
- Verify
expandModeis set to 'Multiple' if multiple should be open - Check event handlers aren't calling
e.cancel = true
---
For detailed information on any aspect, refer to the documentation and navigation guide above. Start with getting-started.md if you're new to the component.
Advanced Features in Angular Accordion
Table of Contents
- Custom Animations
- Animation API Reference
- Nested Accordions
- TreeView Integration
- Custom Styling
- RTL Support
Custom Animations
Animation Configuration
Customize the expand and collapse animations using the animation property:
import { Component } from '@angular/core';
import { AccordionModule } from '@syncfusion/ej2-angular-navigations';
@Component({
selector: 'app-root',
standalone: true,
imports: [AccordionModule],
template: `
<ejs-accordion [animation]="animationSettings">
<e-accordionitems>
<e-accordionitem expanded="true">
<ng-template #header>Animated Item 1</ng-template>
<ng-template #content>Content with custom animation</ng-template>
</e-accordionitem>
<e-accordionitem>
<ng-template #header>Animated Item 2</ng-template>
<ng-template #content>Smooth expand/collapse transitions</ng-template>
</e-accordionitem>
</e-accordionitems>
</ejs-accordion>
`
})
export class AppComponent {
public animationSettings = {
expand: {
effect: 'SlideDown',
duration: 400,
easing: 'ease'
},
collapse: {
effect: 'SlideUp',
duration: 400,
easing: 'ease'
}
};
}Available Animation Effects
The accordion supports various animation effects for expand and collapse:
| Effect | Description |
|---|---|
SlideDown | Content slides down smoothly (default expand) |
SlideUp | Content slides up smoothly (default collapse) |
FadeDown | Content fades in while sliding down |
FadeUp | Content fades out while sliding up |
Zoom | Content zooms in/out |
None | No animation |
Animation Examples
SlideDown and SlideUp (Default):
expand: { effect: 'SlideDown', duration: 400 },
collapse: { effect: 'SlideUp', duration: 400 }FadeDown and FadeUp:
expand: { effect: 'FadeDown', duration: 500 },
collapse: { effect: 'FadeUp', duration: 500 }Zoom Animation:
expand: { effect: 'Zoom', duration: 600, easing: 'ease-in' },
collapse: { effect: 'Zoom', duration: 600, easing: 'ease-out' }No Animation:
expand: { effect: 'None' },
collapse: { effect: 'None' }Animation Easing Functions
Control the animation timing curve using easing:
| Easing | Description |
|---|---|
linear | Constant speed throughout |
ease | Slow start and end, fast middle |
ease-in | Slow start, fast end |
ease-out | Fast start, slow end |
ease-in-out | Slow start and end |
public animationSettings = {
expand: {
effect: 'SlideDown',
duration: 400,
easing: 'ease-out' // Fast start, slow end
},
collapse: {
effect: 'SlideUp',
duration: 400,
easing: 'ease-in' // Slow start, fast end
}
};Duration Control
Adjust animation duration in milliseconds:
// Fast animation (200ms)
expand: { effect: 'SlideDown', duration: 200 }
// Normal animation (400ms)
expand: { effect: 'SlideDown', duration: 400 }
// Slow animation (800ms)
expand: { effect: 'SlideDown', duration: 800 }
// No delay animation (0ms)
expand: { effect: 'SlideDown', duration: 0 }Complete Animation Example
import { Component, ViewChild } from '@angular/core';
import { AccordionModule, AccordionComponent } from '@syncfusion/ej2-angular-navigations';
@Component({
selector: 'app-root',
standalone: true,
imports: [AccordionModule],
template: `
<div style="margin-bottom: 20px;">
<label>Select Animation Effect:
<select (change)="updateAnimation()">
<option value="SlideDown">SlideDown/SlideUp</option>
<option value="FadeDown">FadeDown/FadeUp</option>
<option value="Zoom">Zoom</option>
<option value="None">None</option>
</select>
</label>
</div>
<ejs-accordion #accordion [animation]="animationSettings">
<e-accordionitems>
<e-accordionitem expanded="true">
<ng-template #header>Item 1</ng-template>
<ng-template #content>Animated Content 1</ng-template>
</e-accordionitem>
<e-accordionitem>
<ng-template #header>Item 2</ng-template>
<ng-template #content>Animated Content 2</ng-template>
</e-accordionitem>
</e-accordionitems>
</ejs-accordion>
`
})
export class AppComponent {
@ViewChild('accordion') accordionObj?: AccordionComponent;
public selectedEffect = 'SlideDown';
public animationSettings = {
expand: { effect: 'SlideDown', duration: 400 },
collapse: { effect: 'SlideUp', duration: 400 }
};
updateAnimation() {
const expandEffect = this.selectedEffect;
const collapseEffect = this.selectedEffect === 'SlideDown' ? 'SlideUp' :
this.selectedEffect === 'FadeDown' ? 'FadeUp' :
this.selectedEffect;
this.animationSettings = {
expand: { effect: expandEffect as any, duration: 400 },
collapse: { effect: collapseEffect as any, duration: 400 }
};
}
}Animation API Reference
The animation system consists of two models: AccordionAnimationSettingsModel (top-level) and AccordionActionSettingsModel (individual actions).
animation Property (AccordionAnimationSettingsModel)
Type: AccordionAnimationSettingsModel
Configures both expand and collapse animation behaviors.
expand Sub-Property (AccordionActionSettingsModel)
Type: AccordionActionSettingsModel Description: Specifies animation for expanding accordion items
Properties:
effect: Animation effect type ('SlideDown' | 'SlideUp' | 'FadeDown' | 'FadeUp' | 'Zoom' | 'None')duration: Animation duration in milliseconds (number, default: 400)easing: Animation timing function (string, default: 'linear')
Default: { effect: 'SlideDown', duration: 400, easing: 'linear' }
collapse Sub-Property (AccordionActionSettingsModel)
Type: AccordionActionSettingsModel Description: Specifies animation for collapsing accordion items
Properties:
effect: Animation effect typeduration: Animation duration in millisecondseasing: Animation timing function
Default: { effect: 'SlideUp', duration: 400, easing: 'linear' }
Complete Animation Property Example
animation: {
expand: {
effect: 'SlideDown', // When expanding
duration: 400, // Milliseconds
easing: 'ease-out' // Timing curve
},
collapse: {
effect: 'SlideUp', // When collapsing
duration: 400, // Milliseconds
easing: 'ease-in' // Timing curve
}
}All Animation Effects Reference
| Effect | Best For | Example | Notes |
|---|---|---|---|
SlideDown | Expand action | Content slides down smoothly | Default expand effect |
SlideUp | Collapse action | Content slides up smoothly | Default collapse effect |
FadeDown | Professional look | Content fades in while sliding | Good for subtle animations |
FadeUp | Professional look | Content fades out while sliding | Pairs with FadeDown |
Zoom | Attention-grabbing | Content zooms from center | Most dramatic effect |
None | No animation | Instant expand/collapse | Best for performance |
All Easing Functions Reference
| Easing | Curve | Best For | Use Case |
|---|---|---|---|
linear | Constant speed | Simple animations | Straightforward expand/collapse |
ease | Slow start/end, fast middle | Default behavior | Balanced feel |
ease-in | Accelerating | Collapse action | Speeds up as it closes |
ease-out | Decelerating | Expand action | Slows down as it opens |
ease-in-out | Slow start and end | Symmetric animations | Equal timing both directions |
Effect-Easing Combinations
Recommended Combinations:
// Smooth & Professional
animation: {
expand: { effect: 'SlideDown', duration: 400, easing: 'ease-out' },
collapse: { effect: 'SlideUp', duration: 400, easing: 'ease-in' }
}
// Fast & Responsive
animation: {
expand: { effect: 'SlideDown', duration: 250, easing: 'ease-out' },
collapse: { effect: 'SlideUp', duration: 250, easing: 'ease-in' }
}
// Fade Effect
animation: {
expand: { effect: 'FadeDown', duration: 500, easing: 'ease' },
collapse: { effect: 'FadeUp', duration: 500, easing: 'ease' }
}
// Dramatic Zoom
animation: {
expand: { effect: 'Zoom', duration: 600, easing: 'ease-in-out' },
collapse: { effect: 'Zoom', duration: 600, easing: 'ease-in-out' }
}
// No Animation (Performance)
animation: {
expand: { effect: 'None' },
collapse: { effect: 'None' }
}Duration Edge Cases
// Instant (0ms)
expand: { effect: 'SlideDown', duration: 0 }
// Very Fast (100ms)
expand: { effect: 'SlideDown', duration: 100 }
// Very Slow (1000ms)
expand: { effect: 'SlideDown', duration: 1000 }
// Note: Durations > 5000ms may feel unresponsiveDynamic Animation Updates
Change animations at runtime:
import { Component, ViewChild } from '@angular/core';
import { AccordionModule, AccordionComponent } from '@syncfusion/ej2-angular-navigations';
@Component({
selector: 'app-dynamic-animation',
standalone: true,
imports: [AccordionModule],
template: `
<button (click)="setFastAnimation()">Fast Animation</button>
<button (click)="setSlowAnimation()">Slow Animation</button>
<button (click)="disableAnimation()">No Animation</button>
<ejs-accordion #accordion [animation]="currentAnimation" [items]="items"></ejs-accordion>
`
})
export class AppComponent {
@ViewChild('accordion') accordionObj?: AccordionComponent;
public items = [
{ header: 'Item 1', content: 'Content 1' },
{ header: 'Item 2', content: 'Content 2' }
];
public currentAnimation = {
expand: { effect: 'SlideDown', duration: 400, easing: 'ease-out' },
collapse: { effect: 'SlideUp', duration: 400, easing: 'ease-in' }
};
setFastAnimation() {
this.currentAnimation = {
expand: { effect: 'SlideDown', duration: 200, easing: 'ease-out' },
collapse: { effect: 'SlideUp', duration: 200, easing: 'ease-in' }
};
}
setSlowAnimation() {
this.currentAnimation = {
expand: { effect: 'SlideDown', duration: 800, easing: 'ease-out' },
collapse: { effect: 'SlideUp', duration: 800, easing: 'ease-in' }
};
}
disableAnimation() {
this.currentAnimation = {
expand: { effect: 'None' },
collapse: { effect: 'None' }
};
}
}Nested Accordions
Creating Nested Accordion Structure
Place an accordion inside another accordion's content using ng-template:
import { Component } from '@angular/core';
import { AccordionModule } from '@syncfusion/ej2-angular-navigations';
@Component({
selector: 'app-root',
standalone: true,
imports: [AccordionModule],
template: `
<ejs-accordion>
<e-accordionitems>
<!-- Parent Item 1 -->
<e-accordionitem expanded="true">
<ng-template #header>
<div>Video</div>
</ng-template>
<ng-template #content>
<!-- Nested Accordion -->
<ejs-accordion>
<e-accordionitems>
<e-accordionitem>
<ng-template #header>
<div>Video Track 1</div>
</ng-template>
<ng-template #content>Video Track 1 Content</ng-template>
</e-accordionitem>
<e-accordionitem>
<ng-template #header>
<div>Video Track 2</div>
</ng-template>
<ng-template #content>Video Track 2 Content</ng-template>
</e-accordionitem>
</e-accordionitems>
</ejs-accordion>
</ng-template>
</e-accordionitem>
<!-- Parent Item 2 -->
<e-accordionitem>
<ng-template #header>
<div>Music</div>
</ng-template>
<ng-template #content>
<!-- Nested Accordion -->
<ejs-accordion>
<e-accordionitems>
<e-accordionitem>
<ng-template #header>
<div>Music Track 1</div>
</ng-template>
<ng-template #content>Music Track 1 Content</ng-template>
</e-accordionitem>
<e-accordionitem>
<ng-template #header>
<div>Music Track 2</div>
</ng-template>
<ng-template #content>Music Track 2 Content</ng-template>
</e-accordionitem>
</e-accordionitems>
</ejs-accordion>
</ng-template>
</e-accordionitem>
</e-accordionitems>
</ejs-accordion>
`
})
export class AppComponent {}Multi-Level Nesting
Create deeper hierarchies with three or more levels:
<ejs-accordion>
<e-accordionitems>
<e-accordionitem expanded="true">
<ng-template #header>Level 1 - Item 1</ng-template>
<ng-template #content>
<!-- Level 2 Accordion -->
<ejs-accordion>
<e-accordionitems>
<e-accordionitem expanded="true">
<ng-template #header>Level 2 - Item 1</ng-template>
<ng-template #content>
<!-- Level 3 Accordion -->
<ejs-accordion>
<e-accordionitems>
<e-accordionitem>
<ng-template #header>Level 3 - Item 1</ng-template>
<ng-template #content>Deepest Content</ng-template>
</e-accordionitem>
</e-accordionitems>
</ejs-accordion>
</ng-template>
</e-accordionitem>
</e-accordionitems>
</ejs-accordion>
</ng-template>
</e-accordionitem>
</e-accordionitems>
</ejs-accordion>Nested Accordion with Different Expand Modes
Parent in Single mode, children in Multiple mode:
<ejs-accordion expandMode="Single">
<e-accordionitems>
<e-accordionitem expanded="true">
<ng-template #header>Parent (Single Mode)</ng-template>
<ng-template #content>
<!-- Child in Multiple mode -->
<ejs-accordion expandMode="Multiple">
<e-accordionitems>
<e-accordionitem expanded="true">
<ng-template #header>Child 1 (Multiple)</ng-template>
<ng-template #content>Can expand multiple items</ng-template>
</e-accordionitem>
<e-accordionitem expanded="true">
<ng-template #header>Child 2 (Multiple)</ng-template>
<ng-template #content>Both can be open</ng-template>
</e-accordionitem>
</e-accordionitems>
</ejs-accordion>
</ng-template>
</e-accordionitem>
</e-accordionitems>
</ejs-accordion>TreeView Integration
Embed TreeView in Accordion
Display hierarchical data using TreeView inside accordion items:
import { Component } from '@angular/core';
import { AccordionModule, TreeViewAllModule } from '@syncfusion/ej2-angular-navigations';
@Component({
selector: 'app-root',
standalone: true,
imports: [AccordionModule, TreeViewAllModule],
template: `
<ejs-accordion>
<e-accordionitems>
<e-accordionitem expanded="true">
<ng-template #header>
<div>Documents</div>
</ng-template>
<ng-template #content>
<!-- TreeView inside accordion -->
<ejs-treeview
id="docTree"
[fields]="docFields"
[dataSource]="docData">
</ejs-treeview>
</ng-template>
</e-accordionitem>
<e-accordionitem>
<ng-template #header>
<div>Downloads</div>
</ng-template>
<ng-template #content>
<ejs-treeview
id="downTree"
[fields]="downFields"
[dataSource]="downData">
</ejs-treeview>
</ng-template>
</e-accordionitem>
</e-accordionitems>
</ejs-accordion>
`
})
export class AppComponent {
public docFields = { dataSource: [], id: 'id', text: 'name', child: 'subItems' };
public downFields = { dataSource: [], id: 'id', text: 'name', child: 'subItems' };
public docData = [
{ id: '1', name: 'folder.txt' },
{ id: '2', name: 'report.pdf' }
];
public downData = [
{ id: '1', name: 'app.zip' },
{ id: '2', name: 'data.xlsx' }
];
}TreeView with Hierarchical Data
public fileSystemData = [
{
id: '1',
name: 'Documents',
expanded: true,
subItems: [
{ id: '1-1', name: 'Reports', subItems: [
{ id: '1-1-1', name: 'Q1.pdf' },
{ id: '1-1-2', name: 'Q2.pdf' }
]},
{ id: '1-2', name: 'Proposals' }
]
},
{
id: '2',
name: 'Downloads',
subItems: [
{ id: '2-1', name: 'Software' },
{ id: '2-2', name: 'Updates' }
]
}
];Custom Styling
Apply CSS Classes
Use cssClass to apply custom styling to accordion items:
import { Component } from '@angular/core';
import { AccordionModule } from '@syncfusion/ej2-angular-navigations';
@Component({
selector: 'app-root',
standalone: true,
imports: [AccordionModule],
template: `
<ejs-accordion cssClass="custom-accordion">
<e-accordionitems>
<e-accordionitem expanded="true">
<ng-template #header>Styled Item</ng-template>
<ng-template #content>Custom styled content</ng-template>
</e-accordionitem>
</e-accordionitems>
</ejs-accordion>
`,
styles: [`
:host ::ng-deep .custom-accordion {
border: 2px solid #007bff;
border-radius: 8px;
}
:host ::ng-deep .custom-accordion .e-acrdn-item {
text-align: center;
background-color: #f8f9fa;
}
:host ::ng-deep .custom-accordion .e-acrdn-item.e-select > .e-acrdn-header {
background: #007bff;
color: white;
}
`]
})
export class AppComponent {}Style Accordion Headers
styles: [`
:host ::ng-deep .e-accordion .e-acrdn-item.e-select > .e-acrdn-header {
background: linear-gradient(to right, #667eea 0%, #764ba2 100%);
color: white;
font-weight: bold;
}
:host ::ng-deep .e-accordion .e-acrdn-header {
padding: 15px;
cursor: pointer;
}
:host ::ng-deep .e-accordion .e-acrdn-header:hover {
background-color: #f0f0f0;
}
`]Style Icons
styles: [`
:host ::ng-deep .e-accordion .e-toggle-icon .e-icons {
color: #667eea;
font-size: 18px;
}
:host ::ng-deep .e-accordion .e-acrdn-item.e-select .e-toggle-icon .e-icons {
color: white;
}
`]Complete Styling Example
import { Component } from '@angular/core';
import { AccordionModule } from '@syncfusion/ej2-angular-navigations';
@Component({
selector: 'app-root',
standalone: true,
imports: [AccordionModule],
template: `
<ejs-accordion cssClass="premium-accordion">
<e-accordionitems>
<e-accordionitem expanded="true">
<ng-template #header>Premium Item 1</ng-template>
<ng-template #content>Premium styled content with custom theme</ng-template>
</e-accordionitem>
<e-accordionitem>
<ng-template #header>Premium Item 2</ng-template>
<ng-template #content>More premium styled content</ng-template>
</e-accordionitem>
</e-accordionitems>
</ejs-accordion>
`,
styles: [`
:host ::ng-deep .premium-accordion {
border: none;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
border-radius: 12px;
overflow: hidden;
}
:host ::ng-deep .premium-accordion .e-acrdn-item {
border-bottom: 1px solid #e0e0e0;
}
:host ::ng-deep .premium-accordion .e-acrdn-item.e-select > .e-acrdn-header {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
}
:host ::ng-deep .premium-accordion .e-acrdn-header {
padding: 16px 20px;
font-weight: 500;
transition: all 0.3s ease;
}
:host ::ng-deep .premium-accordion .e-acrdn-content {
padding: 20px;
color: #333;
line-height: 1.6;
}
`]
})
export class AppComponent {}RTL Support
Enable Right-to-Left Layout
Set enableRtl to enable RTL rendering:
import { Component } from '@angular/core';
import { AccordionModule } from '@syncfusion/ej2-angular-navigations';
@Component({
selector: 'app-root',
standalone: true,
imports: [AccordionModule],
template: `
<ejs-accordion [enableRtl]="true">
<e-accordionitems>
<e-accordionitem expanded="true">
<ng-template #header>
<div>عنصر 1</div>
</ng-template>
<ng-template #content>
<div>محتوى باللغة العربية</div>
</ng-template>
</e-accordionitem>
<e-accordionitem>
<ng-template #header>
<div>عنصر 2</div>
</ng-template>
<ng-template #content>
<div>محتوى إضافي</div>
</ng-template>
</e-accordionitem>
</e-accordionitems>
</ejs-accordion>
`
})
export class AppComponent {}Dynamic RTL Toggle
import { Component, ViewChild } from '@angular/core';
import { AccordionModule, AccordionComponent } from '@syncfusion/ej2-angular-navigations';
@Component({
selector: 'app-root',
standalone: true,
imports: [AccordionModule],
template: `
<button (click)="toggleRTL()">
{{ isRTL ? 'Switch to LTR' : 'Switch to RTL' }}
</button>
<ejs-accordion #accordion [enableRtl]="isRTL">
<e-accordionitems>
<e-accordionitem expanded="true">
<ng-template #header>Item 1</ng-template>
<ng-template #content>Content 1</ng-template>
</e-accordionitem>
</e-accordionitems>
</ejs-accordion>
`
})
export class AppComponent {
@ViewChild('accordion') accordionObj?: AccordionComponent;
public isRTL = false;
toggleRTL() {
this.isRTL = !this.isRTL;
}
}RTL with Arabic Content
template: `
<ejs-accordion [enableRtl]="true" lang="ar">
<e-accordionitems>
<e-accordionitem expanded="true">
<ng-template #header>
<div>معلومات المنتج</div>
</ng-template>
<ng-template #content>
<div>
<p>اسم المنتج: منتج عالي الجودة</p>
<p>السعر: 99.99 دولار</p>
<p>التوفر: متوفر الآن</p>
</div>
</ng-template>
</e-accordionitem>
</e-accordionitems>
</ejs-accordion>
`Data Binding in Angular Accordion
Table of Contents
- Overview
- DataSource API Property
- Basic Array Binding
- Object Array Binding
- DataManager and OData Integration
- Handling Response Data
- Refresh After Updates
Overview
Data binding connects your accordion items to data sources, enabling:
- Loading accordion items from arrays
- Fetching data from OData services
- Dynamic data transformation
- Real-time content updates
The accordion uses header and content properties to map data fields to item headers and content.
DataSource API Property
dataSource Property
Type: DataManager | Object[]
Specifies the data source for accordion items. Can be:
- Local array of objects
DataManagerinstance for OData/REST API binding- Remote data URL
Examples:
// Local array
dataSource = [
{ header: 'Item 1', content: 'Content 1' },
{ header: 'Item 2', content: 'Content 2' }
];
<ejs-accordion [dataSource]="dataSource"></ejs-accordion>// DataManager with OData
import { DataManager, ODataV4Adaptor } from '@syncfusion/ej2-data';
public dataSource = new DataManager({
url: 'https://services.odata.org/V4/Northwind/Northwind.svc/Customers',
adaptor: new ODataV4Adaptor()
});
<ejs-accordion [dataSource]="dataSource"></ejs-accordion>Property Mapping for dataSource
When using dataSource, map your data fields to accordion properties using e-accordionitem:
import { Component } from '@angular/core';
import { AccordionModule } from '@syncfusion/ej2-angular-navigations';
import { CommonModule } from '@angular/common';
@Component({
selector: 'app-datasource',
standalone: true,
imports: [AccordionModule, CommonModule],
template: `
<ejs-accordion [dataSource]="dataSource">
<e-accordionitems>
<e-accordionitem
textContent="name"
[content]="'description'">
</e-accordionitem>
</e-accordionitems>
</ejs-accordion>
`
})
export class AppComponent {
public dataSource = [
{ name: 'Product A', description: 'Description for Product A' },
{ name: 'Product B', description: 'Description for Product B' },
{ name: 'Product C', description: 'Description for Product C' }
];
}items vs dataSource Properties
| Aspect | items | dataSource |
|---|---|---|
| Type | AccordionItemModel[] | `DataManager \ |
| Best For | Simple static/dynamic arrays | OData/REST API integration |
| Binding | Direct property binding | Property mapping support |
| Remote Data | Manual handling | Built-in support |
| Usage | [items]="myArray" | [dataSource]="myDataManager" |
items Property
Type: AccordionItemModel[]
Direct array of accordion items with full control over each property.
Example:
public items: AccordionItemModel[] = [
{
header: 'Item 1',
content: 'Content 1',
expanded: true,
disabled: false,
cssClass: 'custom-item'
}
];
<ejs-accordion [items]="items"></ejs-accordion>Basic Array Binding
Simple String Array
Bind accordion items directly to an array of objects:
import { Component } from '@angular/core';
import { AccordionModule } from '@syncfusion/ej2-angular-navigations';
@Component({
selector: 'app-root',
standalone: true,
imports: [AccordionModule],
template: `<ejs-accordion [items]="accordionItems"></ejs-accordion>`
})
export class AppComponent {
public accordionItems = [
{
header: 'ASP.NET',
content: 'Microsoft ASP.NET is a set of technologies...',
expanded: true
},
{
header: 'ASP.NET MVC',
content: 'The Model-View-Controller (MVC) pattern...'
},
{
header: 'JavaScript',
content: 'JavaScript is an interpreted programming language...'
}
];
}Dynamic Array
Update items array at runtime:
import { Component, OnInit } from '@angular/core';
import { AccordionModule } from '@syncfusion/ej2-angular-navigations';
@Component({
selector: 'app-root',
standalone: true,
imports: [AccordionModule],
template: `<ejs-accordion [items]="accordionItems"></ejs-accordion>`
})
export class AppComponent implements OnInit {
public accordionItems: any[] = [];
ngOnInit() {
// Load data on component initialization
this.loadData();
}
loadData() {
this.accordionItems = [
{ header: 'Q1 Results', content: 'First quarter performance data' },
{ header: 'Q2 Results', content: 'Second quarter performance data' },
{ header: 'Q3 Results', content: 'Third quarter performance data' }
];
}
}Object Array Binding
Mapping Custom Properties
Map your data object properties to accordion header and content:
import { Component } from '@angular/core';
import { AccordionModule } from '@syncfusion/ej2-angular-navigations';
@Component({
selector: 'app-root',
standalone: true,
imports: [AccordionModule],
template: `<ejs-accordion [items]="employees"></ejs-accordion>`
})
export class AppComponent {
public employees = [
{
// Map 'name' to header, 'department' to content
header: 'John Smith',
content: 'Engineering Department - Senior Developer'
},
{
header: 'Jane Doe',
content: 'Sales Department - Account Manager'
},
{
header: 'Michael Johnson',
content: 'HR Department - Recruiter'
}
];
}Dynamic Property Mapping
Transform data structure to match accordion requirements:
import { Component, OnInit } from '@angular/core';
import { AccordionModule } from '@syncfusion/ej2-angular-navigations';
interface Employee {
id: number;
firstName: string;
lastName: string;
role: string;
department: string;
}
@Component({
selector: 'app-root',
standalone: true,
imports: [AccordionModule],
template: `<ejs-accordion [items]="accordionItems"></ejs-accordion>`
})
export class AppComponent implements OnInit {
public accordionItems: any[] = [];
ngOnInit() {
this.loadEmployees();
}
loadEmployees() {
const employees: Employee[] = [
{ id: 1, firstName: 'John', lastName: 'Smith', role: 'Developer', department: 'Engineering' },
{ id: 2, firstName: 'Jane', lastName: 'Doe', role: 'Manager', department: 'Sales' },
{ id: 3, firstName: 'Mike', lastName: 'Johnson', role: 'Recruiter', department: 'HR' }
];
// Transform to accordion format
this.accordionItems = employees.map(emp => ({
header: `${emp.firstName} ${emp.lastName}`,
content: `${emp.role} in ${emp.department} Department`,
expanded: emp.id === 1 // First item expanded
}));
}
}DataManager and OData Integration
Install Required Packages
Ensure both packages are installed:
npm install @syncfusion/ej2-angular-navigations @syncfusion/ej2-data --saveFetch Data from OData Service
import { Component, OnInit, ViewChild } from '@angular/core';
import { AccordionModule, AccordionComponent } from '@syncfusion/ej2-angular-navigations';
import { DataManager, Query, ODataV4Adaptor, ReturnOption } from '@syncfusion/ej2-data';
const SERVICE_URI = 'https://services.odata.org/V4/Northwind/Northwind.svc/Employees';
@Component({
selector: 'app-root',
standalone: true,
imports: [AccordionModule],
template: `<ejs-accordion #accordion></ejs-accordion>`
})
export class AppComponent implements OnInit {
@ViewChild('accordion') accordionObj?: AccordionComponent;
public itemsData: any[] = [];
public mapping = { header: 'FirstName', content: 'Notes' };
ngOnInit() {
this.loadODataEmployees();
}
loadODataEmployees() {
// Create DataManager with OData service
new DataManager({
url: SERVICE_URI,
adaptor: new ODataV4Adaptor()
})
.executeQuery(new Query().range(1, 4)) // Fetch first 4 employees
.then((e: ReturnOption) => {
let result: any = e.result;
// Transform OData response to accordion format
for (let i = 0; i < result.length; i++) {
this.itemsData.push({
header: result[i][this.mapping.header],
content: result[i][this.mapping.content],
expanded: i === 0 // First item expanded
});
}
// Set items on accordion
if (this.accordionObj) {
this.accordionObj.items = this.itemsData;
this.accordionObj.refresh();
}
});
}
}OData Query Examples
Fetch specific number of records:
.executeQuery(new Query().range(0, 10)) // First 10 recordsFilter records:
.executeQuery(new Query().where('City', 'equal', 'Seattle'))Sort records:
.executeQuery(new Query().sortBy('FirstName', 'ascending'))Combine queries:
.executeQuery(
new Query()
.where('City', 'equal', 'Seattle')
.sortBy('LastName')
.range(0, 5)
)REST API Data Binding
Fetch data from your custom REST API:
import { Component, OnInit, ViewChild } from '@angular/core';
import { AccordionModule, AccordionComponent } from '@syncfusion/ej2-angular-navigations';
import { HttpClient } from '@angular/common/http';
interface ApiResponse {
id: number;
title: string;
description: string;
}
@Component({
selector: 'app-root',
standalone: true,
imports: [AccordionModule],
template: `<ejs-accordion #accordion [items]="accordionItems"></ejs-accordion>`
})
export class AppComponent implements OnInit {
@ViewChild('accordion') accordionObj?: AccordionComponent;
public accordionItems: any[] = [];
constructor(private http: HttpClient) {}
ngOnInit() {
this.loadApiData();
}
loadApiData() {
this.http.get<ApiResponse[]>('/api/articles')
.subscribe(
(data: ApiResponse[]) => {
this.accordionItems = data.map(item => ({
header: item.title,
content: item.description,
expanded: false
}));
},
(error) => {
console.error('Error loading data:', error);
}
);
}
}Handling Response Data
Transform Complex Response
When API returns nested or complex data structures:
import { Component, OnInit, ViewChild } from '@angular/core';
import { AccordionModule, AccordionComponent } from '@syncfusion/ej2-angular-navigations';
import { HttpClient } from '@angular/common/http';
interface ComplexResponse {
success: boolean;
message: string;
data: {
id: number;
name: string;
details: string;
metadata?: { category: string };
}[];
}
@Component({
selector: 'app-root',
standalone: true,
imports: [AccordionModule],
template: `<ejs-accordion #accordion [items]="accordionItems"></ejs-accordion>`
})
export class AppComponent implements OnInit {
@ViewChild('accordion') accordionObj?: AccordionComponent;
public accordionItems: any[] = [];
constructor(private http: HttpClient) {}
ngOnInit() {
this.loadComplexData();
}
loadComplexData() {
this.http.get<ComplexResponse>('/api/categories')
.subscribe(
(response: ComplexResponse) => {
if (response.success) {
// Extract data array and transform
this.accordionItems = response.data.map((item, index) => ({
header: `${item.name} (${item.metadata?.category || 'General'})`,
content: item.details,
expanded: index === 0
}));
}
},
(error) => {
console.error('Error:', error);
}
);
}
}Error Handling
loadData() {
this.http.get('/api/accordion-items')
.subscribe(
(data: any[]) => {
// Success: transform and set data
this.accordionItems = this.transformData(data);
},
(error: any) => {
// Error handling
console.error('Failed to load data:', error.message);
// Set fallback data or show error message
this.accordionItems = [{
header: 'Error',
content: 'Failed to load accordion data. Please try again later.'
}];
}
);
}
private transformData(data: any[]): any[] {
return data.map(item => ({
header: item.title || 'Untitled',
content: item.body || 'No content available',
expanded: false
}));
}Refresh After Updates
Refresh Accordion After Data Changes
When data changes, refresh the accordion to reflect updates:
import { Component, ViewChild } from '@angular/core';
import { AccordionModule, AccordionComponent } from '@syncfusion/ej2-angular-navigations';
@Component({
selector: 'app-root',
standalone: true,
imports: [AccordionModule],
template: `
<button (click)="updateData()">Update Data</button>
<ejs-accordion #accordion [items]="accordionItems"></ejs-accordion>
`
})
export class AppComponent {
@ViewChild('accordion') accordionObj?: AccordionComponent;
public accordionItems = [
{ header: 'Item 1', content: 'Original content 1' },
{ header: 'Item 2', content: 'Original content 2' }
];
updateData() {
// Modify data
this.accordionItems[0].content = 'Updated content 1';
this.accordionItems[1].content = 'Updated content 2';
// Refresh accordion to reflect changes
if (this.accordionObj) {
this.accordionObj.refresh();
}
}
}Replace Entire Dataset
replaceDataset() {
// New data from API or calculation
this.accordionItems = [
{ header: 'New Item 1', content: 'New content 1', expanded: true },
{ header: 'New Item 2', content: 'New content 2' },
{ header: 'New Item 3', content: 'New content 3' }
];
// Refresh to apply changes
if (this.accordionObj) {
this.accordionObj.items = this.accordionItems;
this.accordionObj.refresh();
}
}Real-Time Updates
For constantly updating data (WebSocket, polling):
import { Component, OnInit, OnDestroy, ViewChild } from '@angular/core';
import { AccordionModule, AccordionComponent } from '@syncfusion/ej2-angular-navigations';
import { interval, Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
@Component({
selector: 'app-root',
standalone: true,
imports: [AccordionModule],
template: `<ejs-accordion #accordion [items]="accordionItems"></ejs-accordion>`
})
export class AppComponent implements OnInit, OnDestroy {
@ViewChild('accordion') accordionObj?: AccordionComponent;
public accordionItems: any[] = [];
private destroy$ = new Subject<void>();
ngOnInit() {
// Poll for updates every 5 seconds
interval(5000)
.pipe(takeUntil(this.destroy$))
.subscribe(() => this.refreshData());
}
refreshData() {
// Fetch latest data
fetch('/api/live-data')
.then(res => res.json())
.then(data => {
this.accordionItems = data.map((item: any) => ({
header: item.title,
content: item.description,
expanded: false
}));
// Refresh accordion
this.accordionObj?.refresh();
});
}
ngOnDestroy() {
this.destroy$.next();
this.destroy$.complete();
}
}Dynamic Loading and Interactions in Angular Accordion
Table of Contents
- Dynamic Item Loading
- Methods API Reference
- Event Handlers
- Event Arguments Reference
- Programmatic Expand/Collapse
- Disabling Items
- Visibility Control (hideItem)
- Focus Management (select)
- Cleanup (destroy)
- Checkbox Integration
- AJAX Content Loading
- Content Projection with ng-content
- Always-Open Accordion Items
- Progressive Content Loading
Dynamic Item Loading
Adding Items at Runtime
Use the addItem() method to add items after the accordion is initialized:
import { Component, ViewChild } from '@angular/core';
import { AccordionModule, AccordionComponent } from '@syncfusion/ej2-angular-navigations';
@Component({
selector: 'app-root',
standalone: true,
imports: [AccordionModule],
template: `
<button (click)="addNewItem()">Add New Item</button>
<ejs-accordion #accordion [items]="items"></ejs-accordion>
`
})
export class AppComponent {
@ViewChild('accordion') accordionObj?: AccordionComponent;
public items = [
{ header: 'Item 1', content: 'Content 1', expanded: true },
{ header: 'Item 2', content: 'Content 2' }
];
addNewItem() {
const newItem = {
header: `Item ${this.items.length + 1}`,
content: `Content ${this.items.length + 1}`
};
// Add item at the end
if (this.accordionObj) {
this.accordionObj.addItem(newItem);
}
}
}Adding Items at Specific Index
addItemAtPosition(index: number) {
const newItem = {
header: 'Inserted Item',
content: 'This item was inserted at position ' + index
};
// Add item at specific index
if (this.accordionObj) {
this.accordionObj.addItem(newItem, index);
}
}Removing Items
removeItem(index: number) {
if (this.accordionObj) {
this.accordionObj.removeItem(index);
}
}
// Remove first item
removeFirstItem() {
this.removeItem(0);
}
// Remove last item
removeLastItem() {
if (this.accordionObj) {
const lastIndex = (this.accordionObj.items || []).length - 1;
this.removeItem(lastIndex);
}
}Methods API Reference
All accordion methods are accessed through the template reference variable #accordion using @ViewChild:
addItem() Method
Signature: addItem(item: AccordionItemModel | AccordionItemModel[] | Object | Object[], index?: number): void
Adds one or more items to the accordion. If index is provided, items are inserted at that position; otherwise, they are appended.
Parameters:
item- Single or array ofAccordionItemModelobjects to addindex(optional) - Zero-based index where items should be inserted
Examples:
// Add single item at end
this.accordionObj?.addItem({ header: 'New Item', content: 'Content' });
// Add single item at index 1
this.accordionObj?.addItem({ header: 'New Item', content: 'Content' }, 1);
// Add multiple items at end
this.accordionObj?.addItem([
{ header: 'Item 1', content: 'Content 1' },
{ header: 'Item 2', content: 'Content 2' }
]);
// Add multiple items at index 0
this.accordionObj?.addItem([
{ header: 'First', content: 'Content' },
{ header: 'Second', content: 'Content' }
], 0);removeItem() Method
Signature: removeItem(index: number): void
Removes an item at the specified index.
Parameters:
index- Zero-based index of item to remove
Examples:
// Remove first item
this.accordionObj?.removeItem(0);
// Remove last item
const lastIndex = (this.accordionObj?.items?.length || 0) - 1;
this.accordionObj?.removeItem(lastIndex);
// Remove with edge case handling
removeItemSafely(index: number) {
if (this.accordionObj && index >= 0 && index < (this.accordionObj.items?.length || 0)) {
this.accordionObj.removeItem(index);
}
}expandItem() Method
Signature: expandItem(isExpand: boolean, index?: number): void
Expands or collapses items. Behavior depends on expand mode and whether index is provided.
Parameters:
isExpand-trueto expand,falseto collapseindex(optional) - Zero-based index of specific item (in Multiple mode, omit to expand/collapse all)
Examples:
// Expand specific item
this.accordionObj?.expandItem(true, 0);
// Collapse specific item
this.accordionObj?.expandItem(false, 0);
// In Multiple mode: expand all items
this.accordionObj?.expandItem(true);
// In Multiple mode: collapse all items
this.accordionObj?.expandItem(false);
// Edge case: index out of range
expandItemSafely(index: number) {
if (this.accordionObj && index >= 0 && index < (this.accordionObj.items?.length || 0)) {
this.accordionObj.expandItem(true, index);
}
}enableItem() Method
Signature: enableItem(index: number, isEnable: boolean): void
Enables or disables an accordion item, controlling whether it can be expanded.
Parameters:
index- Zero-based index of itemisEnable-trueto enable (make clickable),falseto disable (prevent interaction)
Examples:
// Enable item at index 1
this.accordionObj?.enableItem(1, true);
// Disable item at index 2
this.accordionObj?.enableItem(2, false);
// Toggle item enabled state
toggleItemState(index: number) {
if (this.accordionObj?.items?.[index]) {
const isCurrentlyEnabled = !this.accordionObj.items[index].disabled;
this.accordionObj.enableItem(index, !isCurrentlyEnabled);
}
}
// Disable all items except first
disableAllButFirst() {
const itemCount = this.accordionObj?.items?.length || 0;
for (let i = 1; i < itemCount; i++) {
this.accordionObj?.enableItem(i, false);
}
}hideItem() Method
Signature: hideItem(index: number, isHidden?: boolean): void
Shows or hides an accordion item without removing it.
Parameters:
index- Zero-based index of itemisHidden(optional) -trueto hide,falseto show (default: false)
Examples:
// Hide item at index 2
this.accordionObj?.hideItem(2, true);
// Show item at index 2
this.accordionObj?.hideItem(2, false);
// Toggle visibility
toggleItemVisibility(index: number) {
if (this.accordionObj?.items?.[index]) {
const isCurrentlyVisible = !this.accordionObj.items[index].visible;
this.accordionObj.hideItem(index, isCurrentlyVisible);
}
}
// Hide items matching condition
hideItemsByHeader(searchText: string) {
this.accordionObj?.items?.forEach((item, index) => {
if (item.header?.includes(searchText)) {
this.accordionObj?.hideItem(index, true);
}
});
}select() Method
Signature: select(index: number): void
Sets focus to the specified item's header (useful for keyboard navigation and accessibility).
Parameters:
index- Zero-based index of item to focus
Examples:
// Focus first item
this.accordionObj?.select(0);
// Focus next item
focusNextItem() {
// Logic to determine current focused index...
this.accordionObj?.select(currentIndex + 1);
}
// Focus item by condition
focusItemByHeader(headerText: string) {
const index = this.accordionObj?.items?.findIndex(item => item.header === headerText);
if (index !== -1 && index !== undefined) {
this.accordionObj?.select(index);
}
}
// Keyboard navigation pattern
handleKeyDown(event: KeyboardEvent) {
if (event.key === 'ArrowDown') {
// Focus next item
this.accordionObj?.select((this.currentFocusIndex || 0) + 1);
} else if (event.key === 'ArrowUp') {
// Focus previous item
this.accordionObj?.select(Math.max(0, (this.currentFocusIndex || 1) - 1));
}
}destroy() Method
Signature: destroy(): void
Destroys the accordion component, removing it from the DOM and cleaning up all event listeners and resources.
Examples:
// Destroy accordion when component is destroyed
ngOnDestroy() {
if (this.accordionObj) {
this.accordionObj.destroy();
}
}
// Destroy accordion on button click
destroyAccordion() {
if (this.accordionObj) {
this.accordionObj.destroy();
this.accordionObj = undefined;
console.log('Accordion destroyed');
}
}
// Conditional cleanup
cleanupWithLogging() {
if (this.accordionObj) {
console.log('Destroying accordion with', this.accordionObj.items?.length, 'items');
this.accordionObj.destroy();
}
}Event Handlers
Expanding Event
Triggered when an item begins to expand. Use for validation, preventing expansion, or loading content:
import { Component, ViewChild } from '@angular/core';
import { AccordionModule, AccordionComponent } from '@syncfusion/ej2-angular-navigations';
import { ExpandEventArgs } from '@syncfusion/ej2-navigations';
@Component({
selector: 'app-root',
standalone: true,
imports: [AccordionModule],
template: `
<ejs-accordion #accordion (expanding)="onExpanding($event)">
<e-accordionitems>
<e-accordionitem expanded="true">
<ng-template #header>Item 1</ng-template>
<ng-template #content>Content 1</ng-template>
</e-accordionitem>
<e-accordionitem>
<ng-template #header>Item 2</ng-template>
<ng-template #content>Content 2</ng-template>
</e-accordionitem>
</e-accordionitems>
</ejs-accordion>
`
})
export class AppComponent {
@ViewChild('accordion') accordionObj?: AccordionComponent;
onExpanding(event: ExpandEventArgs) {
console.log('Expanding item:', event.item);
// Example: Prevent expansion if condition not met
if (event.item.header === 'Item 1') {
// event.cancel = true; // Uncomment to prevent expansion
}
}
}Expanded Event
Triggered after an item has finished expanding:
onExpanded(event: ExpandEventArgs) {
console.log('Item expanded:', event.item);
// Load content or perform initialization here
}Collapsing and Collapsed Events
onCollapsing(event: ExpandEventArgs) {
console.log('Item about to collapse');
// Prevent collapse if needed
// event.cancel = true;
}
onCollapsed(event: ExpandEventArgs) {
console.log('Item collapsed');
// Cleanup or state management
}Click Event
Triggered when any header or content is clicked:
onClick(event: any) {
console.log('Clicked:', event);
console.log('Item:', event.item);
console.log('Original event:', event.originalEvent);
}Full Event Handler Example
import { Component, ViewChild } from '@angular/core';
import { AccordionModule, AccordionComponent } from '@syncfusion/ej2-angular-navigations';
import { ExpandEventArgs } from '@syncfusion/ej2-navigations';
@Component({
selector: 'app-root',
standalone: true,
imports: [AccordionModule],
template: `
<ejs-accordion
#accordion
(expanding)="onExpanding($event)"
(expanded)="onExpanded($event)"
(collapsing)="onCollapsing($event)"
(collapsed)="onCollapsed($event)"
(clicked)="onClick($event)">
<e-accordionitems>
<e-accordionitem expanded="true">
<ng-template #header>Track Events</ng-template>
<ng-template #content>Watch console for events</ng-template>
</e-accordionitem>
</e-accordionitems>
</ejs-accordion>
`
})
export class AppComponent {
onExpanding(event: ExpandEventArgs) { console.log('expanding'); }
onExpanded(event: ExpandEventArgs) { console.log('expanded'); }
onCollapsing(event: ExpandEventArgs) { console.log('collapsing'); }
onCollapsed(event: ExpandEventArgs) { console.log('collapsed'); }
onClick(event: any) { console.log('clicked'); }
}Event Arguments Reference
ExpandEventArgs Interface
Used by expanding and expanded events. Provides access to the item being expanded/collapsed.
Properties:
| Property | Type | Description |
|---|---|---|
cancel | boolean | Set to true to prevent the expand/collapse action (only in expanding event) |
content | HTMLElement | The DOM element containing the item's content |
element | HTMLElement | The DOM element of the accordion item |
index | number | Zero-based index of the item |
isExpanded | boolean | Current expand state: true if expanding, false if collapsing |
item | AccordionItemModel | The item object being affected |
name | string | Event name ('expanding' or 'expanded') |
Usage Example:
onExpanding(event: ExpandEventArgs) {
console.log(`Item at index ${event.index} is ${event.isExpanded ? 'expanding' : 'collapsing'}`);
console.log('Item header:', event.item.header);
console.log('Content element:', event.content);
// Prevent expansion if needed
if (event.item.disabled) {
event.cancel = true;
}
}AccordionClickArgs Interface
Used by clicked event. Provides access to the item that was clicked.
Properties:
| Property | Type | Description |
|---|---|---|
cancel | boolean | Set to true to prevent the default click behavior |
item | AccordionItemModel | The item object that was clicked |
name | string | Event name ('clicked') |
originalEvent | Event | The original DOM click event |
Usage Example:
onClicked(event: AccordionClickArgs) {
console.log('Clicked item:', event.item.header);
console.log('Mouse X:', (event.originalEvent as MouseEvent).clientX);
console.log('Mouse Y:', (event.originalEvent as MouseEvent).clientY);
// Prevent default action
if (event.item.header === 'Protected') {
event.cancel = true;
}
}Complete Event Arguments Example
import { Component, ViewChild } from '@angular/core';
import { AccordionModule, AccordionComponent } from '@syncfusion/ej2-angular-navigations';
import { ExpandEventArgs, AccordionClickArgs } from '@syncfusion/ej2-navigations';
@Component({
selector: 'app-event-args',
standalone: true,
imports: [AccordionModule],
template: `
<ejs-accordion
#accordion
(expanding)="onExpanding($event)"
(expanded)="onExpanded($event)"
(clicked)="onClicked($event)"
[items]="items">
</ejs-accordion>
<div>Last event: {{ lastEvent }}</div>
`
})
export class AppComponent {
@ViewChild('accordion') accordionObj?: AccordionComponent;
public items = [
{ header: 'Item 1', content: 'Content 1' },
{ header: 'Item 2', content: 'Content 2' },
{ header: 'Item 3', content: 'Content 3' }
];
public lastEvent = '';
onExpanding(event: ExpandEventArgs) {
this.lastEvent = `Expanding item ${event.index} (${event.item.header})`;
console.log('ExpandEventArgs:', {
index: event.index,
name: event.name,
isExpanded: event.isExpanded,
contentElement: event.content
});
}
onExpanded(event: ExpandEventArgs) {
this.lastEvent = `Expanded item ${event.index}`;
}
onClicked(event: AccordionClickArgs) {
this.lastEvent = `Clicked item ${event.item.header}`;
console.log('AccordionClickArgs:', {
item: event.item,
name: event.name,
originalEvent: event.originalEvent
});
}
}Programmatic Expand/Collapse
Expand an Item Programmatically
Use expandItem() to expand a specific item:
expandItem(index: number) {
if (this.accordionObj) {
this.accordionObj.expandItem(true, index); // true to expand
}
}
// Expand first item
expandFirst() {
this.expandItem(0);
}
// Expand specific item by index
expandByIndex(index: number) {
this.expandItem(index);
}Collapse an Item Programmatically
collapseItem(index: number) {
if (this.accordionObj) {
this.accordionObj.expandItem(false, index); // false to collapse
}
}
// Collapse all items
collapseAll() {
if (this.accordionObj && this.accordionObj.items) {
for (let i = 0; i < this.accordionObj.items.length; i++) {
this.accordionObj.expandItem(false, i);
}
}
}Full Expand/Collapse Control Example
import { Component, ViewChild } from '@angular/core';
import { AccordionModule, AccordionComponent } from '@syncfusion/ej2-angular-navigations';
@Component({
selector: 'app-root',
standalone: true,
imports: [AccordionModule],
template: `
<div style="margin-bottom: 20px;">
<button (click)="expandAll()">Expand All</button>
<button (click)="collapseAll()">Collapse All</button>
<button (click)="expandByIndex(1)">Expand Item 2</button>
<button (click)="collapseByIndex(0)">Collapse Item 1</button>
</div>
<ejs-accordion #accordion [items]="items"></ejs-accordion>
`
})
export class AppComponent {
@ViewChild('accordion') accordionObj?: AccordionComponent;
public items = [
{ header: 'Item 1', content: 'Content 1', expanded: true },
{ header: 'Item 2', content: 'Content 2' },
{ header: 'Item 3', content: 'Content 3' }
];
expandAll() {
this.items.forEach((_, index) => {
this.accordionObj?.expandItem(true, index);
});
}
collapseAll() {
this.items.forEach((_, index) => {
this.accordionObj?.expandItem(false, index);
});
}
expandByIndex(index: number) {
this.accordionObj?.expandItem(true, index);
}
collapseByIndex(index: number) {
this.accordionObj?.expandItem(false, index);
}
}Disabling Items
Disable an Item
Use enableItem() to disable/enable items:
disableItem(index: number) {
if (this.accordionObj) {
this.accordionObj.enableItem(false, index); // false to disable
}
}
// Disable first item
disableFirst() {
this.disableItem(0);
}Enable a Disabled Item
enableItem(index: number) {
if (this.accordionObj) {
this.accordionObj.enableItem(true, index); // true to enable
}
}Example: Conditional Item Enabling
import { Component, ViewChild } from '@angular/core';
import { AccordionModule, AccordionComponent } from '@syncfusion/ej2-angular-navigations';
@Component({
selector: 'app-root',
standalone: true,
imports: [AccordionModule],
template: `
<div style="margin-bottom: 20px;">
<label>
<input type="checkbox" [checked]="item2Enabled" (change)="toggleItem2()">
Enable Item 2
</label>
</div>
<ejs-accordion #accordion [items]="items"></ejs-accordion>
`
})
export class AppComponent {
@ViewChild('accordion') accordionObj?: AccordionComponent;
public item2Enabled = false;
public items = [
{ header: 'Item 1', content: 'Content 1', expanded: true },
{ header: 'Item 2', content: 'Content 2' },
{ header: 'Item 3', content: 'Content 3' }
];
toggleItem2() {
this.item2Enabled = !this.item2Enabled;
this.accordionObj?.enableItem(this.item2Enabled, 1);
}
}Visibility Control (hideItem)
Show/Hide Items Dynamically
Use hideItem() to hide or show accordion items without removing them:
import { Component, ViewChild } from '@angular/core';
import { AccordionModule, AccordionComponent } from '@syncfusion/ej2-angular-navigations';
@Component({
selector: 'app-visibility',
standalone: true,
imports: [AccordionModule],
template: `
<div style="margin-bottom: 20px;">
<button (click)="toggleItemVisibility(0)">Toggle Item 1</button>
<button (click)="toggleItemVisibility(1)">Toggle Item 2</button>
<button (click)="showAll()">Show All</button>
<button (click)="hideAll()">Hide All</button>
</div>
<ejs-accordion #accordion [items]="items"></ejs-accordion>
`
})
export class AppComponent {
@ViewChild('accordion') accordionObj?: AccordionComponent;
public items = [
{ header: 'Important', content: 'Content 1', visible: true },
{ header: 'Optional', content: 'Content 2', visible: true },
{ header: 'Advanced', content: 'Content 3', visible: true }
];
toggleItemVisibility(index: number) {
if (this.accordionObj?.items?.[index]) {
const isVisible = this.accordionObj.items[index].visible;
this.accordionObj.hideItem(index, !isVisible);
}
}
showAll() {
this.accordionObj?.items?.forEach((_, index) => {
this.accordionObj?.hideItem(index, false);
});
}
hideAll() {
this.accordionObj?.items?.forEach((_, index) => {
this.accordionObj?.hideItem(index, true);
});
}
}Filtering with hideItem
filterItems(searchText: string) {
this.accordionObj?.items?.forEach((item, index) => {
const matches = item.header?.toLowerCase().includes(searchText.toLowerCase());
this.accordionObj?.hideItem(index, !matches);
});
}Focus Management (select)
Set Focus to Accordion Items
Use select() to programmatically set focus on specific items for keyboard navigation and accessibility:
import { Component, ViewChild } from '@angular/core';
import { AccordionModule, AccordionComponent } from '@syncfusion/ej2-angular-navigations';
@Component({
selector: 'app-focus',
standalone: true,
imports: [AccordionModule],
template: `
<div style="margin-bottom: 20px;">
<button (click)="focusItem(0)">Focus Item 1</button>
<button (click)="focusItem(1)">Focus Item 2</button>
<button (click)="focusItem(2)">Focus Item 3</button>
<button (click)="focusNext()">Focus Next</button>
<button (click)="focusPrevious()">Focus Previous</button>
</div>
<ejs-accordion
#accordion
[items]="items"
(keydown)="onKeyDown($event)">
</ejs-accordion>
`
})
export class AppComponent {
@ViewChild('accordion') accordionObj?: AccordionComponent;
public items = [
{ header: 'Item 1', content: 'Content 1' },
{ header: 'Item 2', content: 'Content 2' },
{ header: 'Item 3', content: 'Content 3' }
];
private currentFocusIndex = 0;
focusItem(index: number) {
if (index >= 0 && index < (this.accordionObj?.items?.length || 0)) {
this.accordionObj?.select(index);
this.currentFocusIndex = index;
}
}
focusNext() {
const nextIndex = (this.currentFocusIndex + 1) % (this.accordionObj?.items?.length || 1);
this.focusItem(nextIndex);
}
focusPrevious() {
const prevIndex = this.currentFocusIndex === 0 ?
((this.accordionObj?.items?.length || 1) - 1) :
this.currentFocusIndex - 1;
this.focusItem(prevIndex);
}
onKeyDown(event: KeyboardEvent) {
if (event.key === 'ArrowDown') {
this.focusNext();
event.preventDefault();
} else if (event.key === 'ArrowUp') {
this.focusPrevious();
event.preventDefault();
}
}
}Cleanup (destroy)
Destroy Accordion Component
Use destroy() to properly clean up the accordion when it's no longer needed:
import { Component, ViewChild, OnDestroy } from '@angular/core';
import { AccordionModule, AccordionComponent } from '@syncfusion/ej2-angular-navigations';
@Component({
selector: 'app-cleanup',
standalone: true,
imports: [AccordionModule],
template: `
<div style="margin-bottom: 20px;">
<button (click)="destroyAccordion()">Destroy Accordion</button>
<button (click)="recreateAccordion()">Recreate Accordion</button>
</div>
<ejs-accordion
#accordion
*ngIf="accordionVisible"
[items]="items">
</ejs-accordion>
<div *ngIf="!accordionVisible">Accordion has been destroyed</div>
`
})
export class AppComponent implements OnDestroy {
@ViewChild('accordion') accordionObj?: AccordionComponent;
public items = [
{ header: 'Item 1', content: 'Content 1' },
{ header: 'Item 2', content: 'Content 2' },
{ header: 'Item 3', content: 'Content 3' }
];
public accordionVisible = true;
destroyAccordion() {
if (this.accordionObj) {
this.accordionObj.destroy();
this.accordionVisible = false;
console.log('Accordion destroyed');
}
}
recreateAccordion() {
this.accordionVisible = true;
console.log('Accordion recreated');
}
ngOnDestroy() {
// Ensure cleanup when component is destroyed
if (this.accordionObj) {
this.accordionObj.destroy();
}
}
}Best Practices for Component Cleanup
@Component({...})
export class MyAccordionComponent implements OnInit, OnDestroy {
@ViewChild('accordion') accordionObj?: AccordionComponent;
ngOnInit() {
// Initialize accordion resources
}
ngOnDestroy() {
// Clean up accordion before component is destroyed
if (this.accordionObj) {
try {
this.accordionObj.destroy();
} catch (error) {
console.error('Error destroying accordion:', error);
}
}
}
}Checkbox Integration
Expand/Collapse Items with Checkbox
Use checkboxes to control which accordion items are open:
import { Component, ViewChild } from '@angular/core';
import { AccordionModule, AccordionComponent } from '@syncfusion/ej2-angular-navigations';
import { CheckBoxModule, CheckBoxComponent } from '@syncfusion/ej2-angular-buttons';
import { ExpandEventArgs } from '@syncfusion/ej2-navigations';
@Component({
selector: 'app-root',
standalone: true,
imports: [AccordionModule, CheckBoxModule],
template: `
<div style="margin-bottom: 20px;">
<label>
<ejs-checkbox #check1 (change)="onCheck1Change()"></ejs-checkbox>
Toggle Item 1
</label>
</div>
<ejs-accordion
#accordion
(expanding)="onExpanding($event)"
(clicked)="onClick($event)">
<e-accordionitems>
<e-accordionitem expanded="true">
<ng-template #header>
<ejs-checkbox #headerCheck1 [checked]="check1Checked"></ejs-checkbox>
Item 1
</ng-template>
<ng-template #content>Content 1</ng-template>
</e-accordionitem>
</e-accordionitems>
</ejs-accordion>
`
})
export class AppComponent {
@ViewChild('accordion') accordionObj?: AccordionComponent;
@ViewChild('check1') check1?: CheckBoxComponent;
public check1Checked = true;
private clickEventArgs: any = null;
onExpanding(event: ExpandEventArgs) {
// Prevent expansion if clicked from header (not checkbox)
if (this.clickEventArgs) {
const checkboxClicked = (this.clickEventArgs.target as HTMLElement)
.closest('.e-checkbox-wrapper');
if (!checkboxClicked) {
event.cancel = true;
}
}
this.clickEventArgs = null;
}
onClick(event: any) {
this.clickEventArgs = event.originalEvent;
}
onCheck1Change() {
this.check1Checked = this.check1?.checked || false;
this.accordionObj?.expandItem(this.check1Checked, 0);
}
}AJAX Content Loading
Load Content via AJAX
Fetch content from server and insert into accordion items:
import { Component, ViewChild } from '@angular/core';
import { AccordionModule, AccordionComponent } from '@syncfusion/ej2-angular-navigations';
import { Ajax } from '@syncfusion/ej2-base';
@Component({
selector: 'app-root',
standalone: true,
imports: [AccordionModule],
template: `
<ejs-accordion #accordion>
<e-accordionitems>
<e-accordionitem header="Department"></e-accordionitem>
<e-accordionitem header="Platform"></e-accordionitem>
<e-accordionitem header="Employee Details"></e-accordionitem>
</e-accordionitems>
</ejs-accordion>
`
})
export class AppComponent {
@ViewChild('accordion') accordionObj?: AccordionComponent;
ngOnInit() {
// Load external HTML content via AJAX
const ajax = new Ajax('./content.html', 'GET', true);
ajax.send().then();
ajax.onSuccess = (data: string) => {
if (this.accordionObj && this.accordionObj.items) {
// Insert loaded content into third item
this.accordionObj.items[2].content = data;
this.accordionObj.refresh();
}
};
}
}Load Content on Expand Event
Load content only when user expands an item:
import { Component, ViewChild } from '@angular/core';
import { AccordionModule, AccordionComponent } from '@syncfusion/ej2-angular-navigations';
import { HttpClient } from '@angular/common/http';
import { ExpandEventArgs } from '@syncfusion/ej2-navigations';
@Component({
selector: 'app-root',
standalone: true,
imports: [AccordionModule],
template: `
<ejs-accordion
#accordion
(expanding)="onExpanding($event)">
<e-accordionitems>
<e-accordionitem header="Load on Expand"></e-accordionitem>
</e-accordionitems>
</ejs-accordion>
`
})
export class AppComponent {
@ViewChild('accordion') accordionObj?: AccordionComponent;
private loadedIndices = new Set<number>();
constructor(private http: HttpClient) {}
onExpanding(event: ExpandEventArgs) {
const itemIndex = this.accordionObj?.items?.indexOf(event.item) ?? -1;
// Only load if not already loaded
if (itemIndex !== -1 && !this.loadedIndices.has(itemIndex)) {
this.http.get(`/api/content/${itemIndex}`, { responseType: 'text' })
.subscribe(
(content: string) => {
if (this.accordionObj?.items?.[itemIndex]) {
this.accordionObj.items[itemIndex].content = content;
this.accordionObj.refresh();
this.loadedIndices.add(itemIndex);
}
},
(error) => {
console.error('Error loading content:', error);
}
);
}
}
}Content Projection with ng-content
Using ng-content for Reusable Content
Project content into accordion items using Angular's ng-content:
// Reusable accordion item component
import { Component, Input } from '@angular/core';
import { AccordionModule } from '@syncfusion/ej2-angular-navigations';
@Component({
selector: 'app-accordion-item',
standalone: true,
imports: [AccordionModule],
template: `
<e-accordionitem [expanded]="expanded">
<ng-template #header>
<div>{{ header }}</div>
</ng-template>
<ng-template #content>
<ng-content></ng-content>
</ng-template>
</e-accordionitem>
`
})
export class AccordionItemComponent {
@Input() header: string = '';
@Input() expanded: boolean = false;
}
// Parent component using reusable items
import { Component } from '@angular/core';
import { AccordionModule } from '@syncfusion/ej2-angular-navigations';
@Component({
selector: 'app-root',
standalone: true,
imports: [AccordionModule, AccordionItemComponent],
template: `
<ejs-accordion>
<app-accordion-item header="Item 1" [expanded]="true">
<p>This is reusable content for Item 1</p>
<button>Action Button</button>
</app-accordion-item>
<app-accordion-item header="Item 2">
<p>Different content for Item 2</p>
<input type="text" placeholder="Enter text">
</app-accordion-item>
<app-accordion-item header="Item 3">
<ul>
<li>List Item 1</li>
<li>List Item 2</li>
</ul>
</app-accordion-item>
</ejs-accordion>
`
})
export class AppComponent {}Always-Open Accordion Items
Keep One Item Always Expanded
Prevent the currently expanded item from collapsing in Single mode:
import { Component, ViewChild } from '@angular/core';
import { AccordionModule, AccordionComponent } from '@syncfusion/ej2-angular-navigations';
import { ExpandEventArgs, AccordionClickArgs } from '@syncfusion/ej2-navigations';
@Component({
selector: 'app-root',
standalone: true,
imports: [AccordionModule],
template: `
<ejs-accordion
#accordion
expandMode="Single"
(expanding)="beforeExpand($event)"
(clicked)="clicked($event)">
<e-accordionitems>
<e-accordionitem expanded="true">
<ng-template #header>Item 1</ng-template>
<ng-template #content>Content 1</ng-template>
</e-accordionitem>
<e-accordionitem>
<ng-template #header>Item 2</ng-template>
<ng-template #content>Content 2</ng-template>
</e-accordionitem>
</e-accordionitems>
</ejs-accordion>
`
})
export class AppComponent {
@ViewChild('accordion') accordionObj?: AccordionComponent;
private clickedElement: HTMLElement | null = null;
clicked(e: AccordionClickArgs) {
this.clickedElement = (e.originalEvent as MouseEvent).target as HTMLElement;
}
beforeExpand(e: ExpandEventArgs) {
const items = this.accordionObj?.element.children;
if (!items) return;
const childrenArray = Array.from(items);
const selectedItems = childrenArray.filter(el =>
el.classList.contains('e-selected')
);
if (selectedItems.length === 1) {
const selectedElement = selectedItems[0].firstChild as HTMLElement;
// If clicking the same header, prevent collapse
if (this.clickedElement === selectedElement) {
e.cancel = true;
}
}
}
}Progressive Content Loading
Load Content Incrementally
Update accordion content as data becomes available:
import { Component, ViewChild } from '@angular/core';
import { AccordionModule, AccordionComponent } from '@syncfusion/ej2-angular-navigations';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-root',
standalone: true,
imports: [AccordionModule],
template: `
<ejs-accordion #accordion [items]="items"></ejs-accordion>
`
})
export class AppComponent {
@ViewChild('accordion') accordionObj?: AccordionComponent;
public items = [
{ header: 'Section 1', content: 'Loading...', expanded: true },
{ header: 'Section 2', content: 'Loading...' },
{ header: 'Section 3', content: 'Loading...' }
];
constructor(private http: HttpClient) {}
ngOnInit() {
this.loadSectionsProgressively();
}
loadSectionsProgressively() {
// Load first section immediately
this.loadSection(0);
// Load remaining sections sequentially
setTimeout(() => this.loadSection(1), 500);
setTimeout(() => this.loadSection(2), 1000);
}
loadSection(index: number) {
this.http.get(`/api/sections/${index}`, { responseType: 'text' })
.subscribe(
(content: string) => {
this.items[index].content = content;
this.accordionObj?.refresh();
},
(error) => {
this.items[index].content = 'Failed to load content';
this.accordionObj?.refresh();
}
);
}
}Expand Modes in Angular Accordion
Table of Contents
- Overview
- Single Expand Mode
- Multiple Expand Mode
- Use Cases
- Performance Considerations
- Switching Modes
- ExpandMode Enum API
- Programmatic Expand/Collapse
Overview
The Accordion component supports two expand modes that control how many items can be open simultaneously:
1. Single Mode - Only one item can be expanded at a time. Opening a new item collapses the previously open item. 2. Multiple Mode - Default behavior. Multiple items can be expanded simultaneously. Clicking an item toggles its state independently.
Set the mode using the expandMode property on the <ejs-accordion> component.
Single Expand Mode
Configuration
Single expand mode allows only one accordion item to be open at a time. When you expand a new item, the currently open item automatically collapses.
import { Component } from '@angular/core';
import { AccordionModule } from '@syncfusion/ej2-angular-navigations';
@Component({
selector: 'app-root',
standalone: true,
imports: [AccordionModule],
template: `
<ejs-accordion expandMode="Single">
<e-accordionitems>
<e-accordionitem expanded="true">
<ng-template #header>
<div>ASP.NET</div>
</ng-template>
<ng-template #content>
<div>Microsoft ASP.NET is a set of technologies in the Microsoft .NET Framework.</div>
</ng-template>
</e-accordionitem>
<e-accordionitem>
<ng-template #header>
<div>ASP.NET MVC</div>
</ng-template>
<ng-template #content>
<div>The Model-View-Controller (MVC) architectural pattern separates an application into three main components.</div>
</ng-template>
</e-accordionitem>
<e-accordionitem>
<ng-template #header>
<div>JavaScript</div>
</ng-template>
<ng-template #content>
<div>JavaScript is an interpreted computer programming language.</div>
</ng-template>
</e-accordionitem>
</e-accordionitems>
</ejs-accordion>
`
})
export class AppComponent {}Initial Expanded Item
Use the expanded property to set which item is initially open:
<ejs-accordion expandMode="Single">
<e-accordionitems>
<e-accordionitem expanded="false">
<ng-template #header>Item 1</ng-template>
<ng-template #content>Content 1</ng-template>
</e-accordionitem>
<e-accordionitem expanded="true"> <!-- This item opens initially -->
<ng-template #header>Item 2</ng-template>
<ng-template #content>Content 2</ng-template>
</e-accordionitem>
</e-accordionitems>
</ejs-accordion>Behavior
- No item initially open: All items start collapsed; user must click to expand
- One item initially open: That item displays expanded; clicking another collapses it
- User interaction: Clicking a header expands it and collapses the previously open item
- Smooth transition: Animation makes the collapse/expand feel natural
Example with Dynamic Items Array
import { Component } from '@angular/core';
import { AccordionModule } from '@syncfusion/ej2-angular-navigations';
@Component({
selector: 'app-root',
standalone: true,
imports: [AccordionModule],
template: `<ejs-accordion expandMode="Single" [items]="items"></ejs-accordion>`
})
export class AppComponent {
public items = [
{ header: 'Technologies', content: 'Web technologies overview', expanded: true },
{ header: 'Languages', content: 'Programming languages guide' },
{ header: 'Frameworks', content: 'Popular frameworks comparison' }
];
}Multiple Expand Mode
Configuration
Multiple expand mode is the default. Any number of accordion items can be open simultaneously. Clicking an item toggles only that item's state without affecting others.
import { Component } from '@angular/core';
import { AccordionModule } from '@syncfusion/ej2-angular-navigations';
@Component({
selector: 'app-root',
standalone: true,
imports: [AccordionModule],
template: `
<ejs-accordion expandMode="Multiple">
<e-accordionitems>
<e-accordionitem expanded="true">
<ng-template #header>
<div>Item 1</div>
</ng-template>
<ng-template #content>
<div>Content 1 - This item is initially open</div>
</ng-template>
</e-accordionitem>
<e-accordionitem>
<ng-template #header>
<div>Item 2</div>
</ng-template>
<ng-template #content>
<div>Content 2 - Click to expand without collapsing Item 1</div>
</ng-template>
</e-accordionitem>
<e-accordionitem>
<ng-template #header>
<div>Item 3</div>
</ng-template>
<ng-template #content>
<div>Content 3 - Can be open alongside Item 1 and Item 2</div>
</ng-template>
</e-accordionitem>
</e-accordionitems>
</ejs-accordion>
`
})
export class AppComponent {}Note: If you omit expandMode, it defaults to Multiple mode.
<!-- These are equivalent: -->
<ejs-accordion expandMode="Multiple"><!-- ... --></ejs-accordion>
<ejs-accordion><!-- ... --></ejs-accordion>Behavior
- Multiple items open: Clicking one doesn't close others
- Toggle behavior: Clicking an open item's header closes it
- Independent state: Each item's open/close state is independent
- All collapsed allowed: All items can be collapsed simultaneously
Example with All Items Initially Expanded
import { Component } from '@angular/core';
import { AccordionModule } from '@syncfusion/ej2-angular-navigations';
@Component({
selector: 'app-root',
standalone: true,
imports: [AccordionModule],
template: `<ejs-accordion expandMode="Multiple" [items]="items"></ejs-accordion>`
})
export class AppComponent {
public items = [
{ header: 'Feature 1', content: 'Description of feature 1', expanded: true },
{ header: 'Feature 2', content: 'Description of feature 2', expanded: true },
{ header: 'Feature 3', content: 'Description of feature 3', expanded: true }
];
}Use Cases
Single Expand Mode Best For:
1. Navigation Menus
- Only one category visible at a time
- Clear navigation flow
- Prevents information overload
expandMode="Single" <!-- User navigates one section at a time -->2. Settings Panels
- Focus user attention on one setting category
- Reduces cognitive load
- Common in mobile interfaces
3. Step-by-Step Wizards
- One step active at a time
- Clear progression through workflow
- Users see one task at a time
4. Content Organization
- When content is mutually exclusive
- Users focus on one topic
- Prevents overwhelming display
Multiple Expand Mode Best For:
1. Comparison Scenarios
- Keep multiple items open to compare
- Users switch between open sections
- Flexible information access
2. FAQ Sections
- Users browse multiple questions simultaneously
- No forced navigation flow
- Natural question-browsing experience
3. Data Exploration
- Multiple data categories visible
- Users explore different aspects
- Comprehensive overview without collapsing
4. Settings with Dependencies
- Multiple related settings visible
- User sees all relevant options
- Helps understand relationships
Performance Considerations
Multiple Mode with Large Datasets
When using Multiple expand mode with many items (50+), consider:
1. Large Content Blocks
- Each open item renders full content
- Multiple expanded items = significant DOM
- Can slow down rendering
2. Performance Optimization Strategies
Option 1: Use Single Mode
expandMode="Single" <!-- Only one item rendered in DOM -->Option 2: Lazy Content Loading
<e-accordionitem>
<ng-template #content>
<!-- Load content on expand event, not upfront -->
</ng-template>
</e-accordionitem>Option 3: Virtualization
- For scrollable accordions with many items
- Render only visible items
- Reduces DOM size
Memory Considerations
- Multiple mode: All open item content in memory
- Single mode: Only one item content in memory
- Dynamic loading: Load content only when needed
Recommendation
For 50+ items, use Single mode or implement lazy loading to ensure smooth performance.
Switching Modes
Change Expand Mode Dynamically
import { Component, ViewChild } from '@angular/core';
import { AccordionModule, AccordionComponent } from '@syncfusion/ej2-angular-navigations';
@Component({
selector: 'app-root',
standalone: true,
imports: [AccordionModule],
template: `
<button (click)="toggleMode()">Switch to {{ currentMode === 'Single' ? 'Multiple' : 'Single' }} Mode</button>
<ejs-accordion #accordion [expandMode]="currentMode">
<e-accordionitems>
<e-accordionitem expanded="true">
<ng-template #header>Item 1</ng-template>
<ng-template #content>Content 1</ng-template>
</e-accordionitem>
<e-accordionitem>
<ng-template #header>Item 2</ng-template>
<ng-template #content>Content 2</ng-template>
</e-accordionitem>
</e-accordionitems>
</ejs-accordion>
`
})
export class AppComponent {
@ViewChild('accordion') accordion?: AccordionComponent;
public currentMode: 'Single' | 'Multiple' = 'Single';
toggleMode() {
this.currentMode = this.currentMode === 'Single' ? 'Multiple' : 'Single';
}
}When you change expandMode, the accordion updates immediately. The current expanded items remain open until the user interacts with them.
ExpandMode Enum API
The expandMode property accepts one of two string values from the ExpandMode enum:
'Single' Mode
Value: 'Single' Behavior: Only one accordion item can be expanded at a time. Default expanded items: Specify via expanded: true on item User action: Expanding one item automatically collapses others
Example:
<ejs-accordion expandMode="Single" [items]="items"></ejs-accordion>'Multiple' Mode
Value: 'Multiple' (Default) Behavior: Multiple accordion items can be expanded simultaneously. Default expanded items: All items with expanded: true open User action: Each item toggles independently
Example:
<ejs-accordion expandMode="Multiple" [items]="items"></ejs-accordion>Or without specifying (uses default):
<ejs-accordion [items]="items"></ejs-accordion>Property Behavior Comparison
| Scenario | Single Mode | Multiple Mode |
|---|---|---|
| Click item 1 | Item 1 expands | Item 1 expands |
| Click item 2 | Item 1 collapses, Item 2 expands | Item 1 stays open, Item 2 expands |
Multiple expanded: true | Only first one opens | All open |
| No initial expanded items | All stay closed | All stay closed |
| Performance with 100+ items | Better (one item open) | May slow down |
Programmatic Expand/Collapse
Use the expandItem() method to control expand mode behavior programmatically:
Expand Specific Item
import { Component, ViewChild } from '@angular/core';
import { AccordionModule, AccordionComponent } from '@syncfusion/ej2-angular-navigations';
@Component({
selector: 'app-expand-item',
standalone: true,
imports: [AccordionModule],
template: `
<button (click)="expandByIndex(1)">Expand Item at Index 1</button>
<button (click)="expandByIndex(2)">Expand Item at Index 2</button>
<ejs-accordion #accordion expandMode="Single" [items]="items"></ejs-accordion>
`
})
export class AppComponent {
@ViewChild('accordion') accordionObj?: AccordionComponent;
public items = [
{ header: 'Item 1', content: 'Content 1' },
{ header: 'Item 2', content: 'Content 2' },
{ header: 'Item 3', content: 'Content 3' }
];
expandByIndex(index: number) {
if (this.accordionObj) {
// In single mode, expanding one item collapses others
this.accordionObj.expandItem(true, index);
}
}
}Expand All Items in Multiple Mode
expandAllItems() {
if (this.accordionObj) {
// Without index parameter, expands all items (Multiple mode only)
this.accordionObj.expandItem(true);
}
}Collapse All Items
collapseAllItems() {
if (this.accordionObj) {
// Collapses all items regardless of mode
this.accordionObj.expandItem(false);
}
}Collapse Specific Item (Multiple Mode Only)
collapseByIndex(index: number) {
if (this.accordionObj) {
// In Multiple mode, can collapse specific item
this.accordionObj.expandItem(false, index);
}
}Example: Mode-Aware Expand Logic
import { Component, ViewChild } from '@angular/core';
import { AccordionModule, AccordionComponent } from '@syncfusion/ej2-angular-navigations';
@Component({
selector: 'app-mode-aware',
standalone: true,
imports: [AccordionModule],
template: `
<ejs-accordion
#accordion
[expandMode]="mode"
[items]="items"
(expanding)="onExpanding($event)">
</ejs-accordion>
`
})
export class AppComponent {
@ViewChild('accordion') accordionObj?: AccordionComponent;
public mode: 'Single' | 'Multiple' = 'Single';
public items = [
{ header: 'Config', content: 'Configuration settings' },
{ header: 'Status', content: 'Current status' },
{ header: 'Logs', content: 'Activity logs' }
];
onExpanding(event: any) {
console.log(`Item ${event.index} expanding in ${this.mode} mode`);
if (this.mode === 'Single') {
console.log('Other items will automatically collapse');
}
}
}Edge Cases and Behavior
Empty Accordion
// No items
const items = [];
<ejs-accordion expandMode="Single" [items]="items"></ejs-accordion>Result: Empty accordion displays, no expand/collapse possible.
All Items Disabled
public items = [
{ header: 'Item 1', content: 'Content', disabled: true },
{ header: 'Item 2', content: 'Content', disabled: true }
];Result: Headers visible but not clickable; expand mode doesn't matter.
Expand Invalid Index
// If items array has 3 items (indices 0-2)
this.accordionObj?.expandItem(true, 5); // Index out of rangeResult: No effect; invalid indices are silently ignored.
Getting Started with Angular Accordion
Table of Contents
- Installation
- Setup
- CSS Configuration
- Basic Template Initialization
- Items Array Initialization
- HTML Elements Initialization
- Core Properties Reference
- AccordionItem Properties
- Running Your Application
Installation
Prerequisites
Ensure you have Node.js and Angular CLI installed on your system.
Install Angular CLI
If you don't have Angular CLI, install it globally:
npm install -g @angular/cliCreate a New Angular Application
Generate a new Angular application:
ng new syncfusion-angular-accordion-appWhen prompted, select your preferred options:
- Stylesheet format: Choose CSS, SCSS, or your preference
- Angular routing: Select based on your needs
- Server-side rendering (SSR): Choose appropriate option
Navigate to your project:
cd syncfusion-angular-accordion-appInstall Syncfusion Accordion Package
Install the @syncfusion/ej2-angular-navigations package:
npm install @syncfusion/ej2-angular-navigations --saveFor Angular versions below 12 (legacy support), use:
npm install @syncfusion/ej2-angular-navigations@ngcc --saveUpdate your package.json with:
"@syncfusion/ej2-angular-navigations": "20.2.38-ngcc"Setup
Import Required Modules
In your component file, import AccordionModule:
import { Component } from '@angular/core';
import { AccordionModule } from '@syncfusion/ej2-angular-navigations';
@Component({
selector: 'app-root',
standalone: true,
imports: [AccordionModule],
template: `<!-- your accordion here -->`
})
export class AppComponent {}CSS Configuration
Add Syncfusion Theme CSS
Add the CSS imports to your main styles file (src/styles.css):
@import '../node_modules/@syncfusion/ej2-base/styles/material3';
@import '../node_modules/@syncfusion/ej2-buttons/styles/material3';
@import '../node_modules/@syncfusion/ej2-popups/styles/material3';
@import '../node_modules/@syncfusion/ej2-navigations/styles/material3';Available Themes:
material3(default modern theme)material(standard Material Design)bootstrap5(Bootstrap 5 theme)fluent(Microsoft Fluent Design)tailwind(Tailwind CSS theme)
Choose based on your application's design system.
Basic Template Initialization
The simplest way to create an accordion using template-based items with ng-template:
import { Component } from '@angular/core';
import { AccordionModule } from '@syncfusion/ej2-angular-navigations';
@Component({
selector: 'app-root',
standalone: true,
imports: [AccordionModule],
template: `
<ejs-accordion>
<e-accordionitems>
<e-accordionitem expanded="true">
<ng-template #header>
<div>ASP.NET</div>
</ng-template>
<ng-template #content>
<div>Microsoft ASP.NET is a set of technologies in the Microsoft .NET Framework for building Web applications and XML Web services. ASP.NET pages execute on the server and generate markup such as HTML, WML, or XML that is sent to a desktop or mobile browser.</div>
</ng-template>
</e-accordionitem>
<e-accordionitem>
<ng-template #header>
<div>ASP.NET MVC</div>
</ng-template>
<ng-template #content>
<div>The Model-View-Controller (MVC) architectural pattern separates an application into three main components: the model, the view, and the controller. The ASP.NET MVC framework provides an alternative to the ASP.NET Web Forms pattern for creating Web applications.</div>
</ng-template>
</e-accordionitem>
<e-accordionitem>
<ng-template #header>
<div>JavaScript</div>
</ng-template>
<ng-template #content>
<div>JavaScript (JS) is an interpreted computer programming language. It was originally implemented as part of web browsers so that client-side scripts could interact with the user, control the browser, communicate asynchronously, and alter the document content.</div>
</ng-template>
</e-accordionitem>
</e-accordionitems>
</ejs-accordion>
`
})
export class AppComponent {}Key points:
- Use
<ejs-accordion>as the root component - Wrap items in
<e-accordionitems> - Each item is
<e-accordionitem> - Set
expanded="true"on initial item to expand it - Use
<ng-template #header>for the header content - Use
<ng-template #content>for the expandable content
Items Array Initialization
Initialize accordion items using a TypeScript array for dynamic or data-driven scenarios:
import { Component } from '@angular/core';
import { AccordionModule } from '@syncfusion/ej2-angular-navigations';
@Component({
selector: 'app-root',
standalone: true,
imports: [AccordionModule],
template: `<ejs-accordion [items]="accordionItems"></ejs-accordion>`
})
export class AppComponent {
public accordionItems = [
{
header: 'ASP.NET',
content: `Microsoft ASP.NET is a set of technologies in the Microsoft .NET Framework for building Web applications and XML Web services. ASP.NET pages execute on the server and generate markup such as HTML, WML, or XML that is sent to a desktop or mobile browser.`,
expanded: true
},
{
header: 'ASP.NET MVC',
content: `The Model-View-Controller (MVC) architectural pattern separates an application into three main components: the model, the view, and the controller. The ASP.NET MVC framework provides an alternative to the ASP.NET Web Forms pattern.`
},
{
header: 'JavaScript',
content: `JavaScript (JS) is an interpreted computer programming language. It was originally implemented as part of web browsers so that client-side scripts could interact with the user, control the browser, and alter the document content.`
}
];
}Advantages:
- Easy to populate from API or database
- Simple data binding
- Scales well for large datasets
- Can be modified at runtime
HTML Elements Initialization
Initialize accordion using plain HTML div elements:
import { Component } from '@angular/core';
import { AccordionModule } from '@syncfusion/ej2-angular-navigations';
@Component({
selector: 'app-root',
standalone: true,
imports: [AccordionModule],
template: `
<ejs-accordion>
<div>
<div>
<div>ASP.NET</div>
</div>
<div>
<div>Microsoft ASP.NET is a set of technologies in the Microsoft .NET Framework for building Web applications and XML Web services.</div>
</div>
</div>
<div>
<div>
<div>ASP.NET MVC</div>
</div>
<div>
<div>The Model-View-Controller (MVC) architectural pattern separates an application into three main components: the model, the view, and the controller.</div>
</div>
</div>
<div>
<div>
<div>JavaScript</div>
</div>
<div>
<div>JavaScript (JS) is an interpreted computer programming language used for creating interactive web pages and applications.</div>
</div>
</div>
</ejs-accordion>
`
})
export class AppComponent {}Structure:
- Item container: outer
<div> - Header container: first inner
<div> - Header text:
<div>inside header container - Content container: second inner
<div> - Content text:
<div>inside content container
Core Properties Reference
The Accordion component uses the following essential properties during initialization:
items Property
Type: AccordionItemModel[]
Specifies the collection of accordion items to display. Each item is an AccordionItemModel object defining header, content, and state.
Example: Using items array with mixed configurations
import { Component } from '@angular/core';
import { AccordionModule } from '@syncfusion/ej2-angular-navigations';
@Component({
selector: 'app-accordion-items',
standalone: true,
imports: [AccordionModule],
template: `<ejs-accordion [items]="items"></ejs-accordion>`
})
export class AppComponent {
public items = [
{ header: 'Item 1', content: 'Content 1', expanded: true },
{ header: 'Item 2', content: 'Content 2', disabled: false },
{ header: 'Item 3', content: 'Content 3', cssClass: 'custom-item' }
];
}expandMode Property
Type: ExpandMode (enum: 'Single' | 'Multiple')
Controls whether one item or multiple items can be expanded simultaneously. Defaults to 'Multiple'.
Example: Setting single expand mode
import { Component } from '@angular/core';
import { AccordionModule } from '@syncfusion/ej2-angular-navigations';
@Component({
selector: 'app-expand-mode',
standalone: true,
imports: [AccordionModule],
template: `<ejs-accordion expandMode="Single" [items]="items"></ejs-accordion>`
})
export class AppComponent {
public items = [
{ header: 'Item 1', content: 'Content 1', expanded: true },
{ header: 'Item 2', content: 'Content 2' },
{ header: 'Item 3', content: 'Content 3' }
];
}headerTemplate Property
Type: string | Function | any
Specifies a custom template for accordion item headers. Allows rich HTML and Angular components.
Example: Custom header template with icons
import { Component } from '@angular/core';
import { AccordionModule } from '@syncfusion/ej2-angular-navigations';
import { CommonModule } from '@angular/common';
@Component({
selector: 'app-header-template',
standalone: true,
imports: [AccordionModule, CommonModule],
template: `
<ejs-accordion [items]="items">
<ng-template #headerTemplate let-data="data">
<span class="icon">{{ data.header }}</span>
</ng-template>
</ejs-accordion>
`
})
export class AppComponent {
public items = [
{ header: '📧 Emails', content: 'Email content here' },
{ header: '📅 Calendar', content: 'Calendar content here' },
{ header: '📝 Tasks', content: 'Tasks content here' }
];
}itemTemplate Property
Type: string | Function | any
Specifies a custom template for accordion item content areas.
Example: Custom content template
import { Component } from '@angular/core';
import { AccordionModule } from '@syncfusion/ej2-angular-navigations';
import { CommonModule } from '@angular/common';
@Component({
selector: 'app-item-template',
standalone: true,
imports: [AccordionModule, CommonModule],
template: `
<ejs-accordion [items]="items">
<ng-template #itemTemplate let-data="data">
<div class="custom-content">
<p>{{ data.description }}</p>
<button>Learn More</button>
</div>
</ng-template>
</ejs-accordion>
`
})
export class AppComponent {
public items = [
{ header: 'Feature 1', description: 'Description for feature 1' },
{ header: 'Feature 2', description: 'Description for feature 2' }
];
}enableRtl Property
Type: boolean
Enables right-to-left (RTL) layout for languages like Arabic, Hebrew, Urdu. Defaults to false.
Example: Enabling RTL support
<ejs-accordion enableRtl="true" [items]="items"></ejs-accordion>enablePersistence Property
Type: boolean
When enabled, saves the expanded/collapsed state in browser localStorage. Defaults to false.
Example: Preserving state across sessions
<ejs-accordion enablePersistence="true" [items]="items"></ejs-accordion>height and width Properties
Type: string | number
Sets the accordion component dimensions. Can be pixel values or percentages.
Example: Setting dimensions
<ejs-accordion
height="500px"
width="100%"
[items]="items">
</ejs-accordion>AccordionItem Properties
Each accordion item uses AccordionItemModel interface with these properties:
header Property
Type: string | HTMLElement | Element
The header text or HTML element displayed for the accordion item.
content Property
Type: string | HTMLElement | Element | Function
The content displayed when the item is expanded. Can be HTML string, DOM element, or function returning content.
Example: Mixed content types
public items = [
{ header: 'Text Header', content: 'Plain text content' },
{ header: 'HTML Header', content: '<strong>HTML</strong> content' },
{ header: 'Dynamic Header', content: () => this.fetchDynamicContent() }
];expanded Property
Type: boolean
Sets initial expanded state of the item. Defaults to false.
Example: Multiple expanded items
public items = [
{ header: 'Item 1', content: 'Content 1', expanded: true },
{ header: 'Item 2', content: 'Content 2', expanded: true },
{ header: 'Item 3', content: 'Content 3', expanded: false }
];disabled Property
Type: boolean
Disables the item, preventing expansion/collapse. Defaults to false.
Example: Disabling specific items
public items = [
{ header: 'Enabled Item', content: 'Can expand', disabled: false },
{ header: 'Disabled Item', content: 'Cannot expand', disabled: true }
];visible Property
Type: boolean
Controls visibility of the item. When false, item is hidden. Defaults to true.
Example: Showing/hiding items
public items = [
{ header: 'Visible Item', content: 'Content here', visible: true },
{ header: 'Hidden Item', content: 'Not shown', visible: false }
];cssClass Property
Type: string
Custom CSS class to apply styling to specific accordion items.
Example: Custom styling
public items = [
{ header: 'Featured', content: 'Special item', cssClass: 'featured-item' },
{ header: 'Standard', content: 'Normal item', cssClass: 'standard-item' }
];In your styles.css:
.featured-item {
background-color: #f0f8ff;
border-left: 4px solid #007bff;
}
.standard-item {
background-color: #ffffff;
}iconCss Property
Type: string
Specifies CSS class for displaying an icon in the accordion item header.
Example: Icons using Font Awesome
public items = [
{ header: 'Settings', content: 'Settings content', iconCss: 'fas fa-cog' },
{ header: 'Users', content: 'Users content', iconCss: 'fas fa-users' },
{ header: 'Reports', content: 'Reports content', iconCss: 'fas fa-chart-bar' }
];id Property
Type: string
Unique identifier for the accordion item, useful for referencing items programmatically.
Example: Item identification
public items = [
{ id: 'item-1', header: 'Item 1', content: 'Content 1' },
{ id: 'item-2', header: 'Item 2', content: 'Content 2' },
{ id: 'item-3', header: 'Item 3', content: 'Content 3' }
];Running Your Application
Start Development Server
Run your application:
npm startOr using ng command:
ng serveThe application will be available at http://localhost:4200
Verify Accordion Renders
Open your browser to http://localhost:4200 and verify:
- All accordion items display with headers
- First item is expanded (showing content)
- Other items are collapsed
- Headers can be clicked to expand/collapse
Next Steps
- Read expand-modes.md to control single vs. multiple expansion
- Read data-binding.md to load data from external sources
- Read dynamic-loading-and-interactions.md for event handling and dynamic updates
- Read advanced-features.md for animations and nested accordions