Creating a Custom Accordion Component in Angular for Faqs

Creating an interactive FAQ section on your website can greatly enhance user experience by allowing visitors to find answers quickly. Angular provides powerful tools to build custom components, such as an accordion, to display FAQs efficiently. This guide will walk you through creating a custom accordion component in Angular tailored for FAQs.

Setting Up Your Angular Environment

Before starting, ensure you have Angular CLI installed. If not, install it using:

npm install -g @angular/cli

Create a new Angular project:

ng new faq-accordion

Navigate into your project directory:

cd faq-accordion

Creating the Accordion Component

Generate a new component called accordion:

ng generate component accordion

Designing the Accordion Template

Open accordion.component.html and add the following code to create a collapsible FAQ item:

<div class="accordion">

<div class="accordion-item" *ngFor="let item of faqs">

<div class="accordion-header" (click)="toggle(item)">{{item.question}}</div>

<div class="accordion-body" [hidden]="!item.open">{{item.answer}}</div>

</div>

</div>

Adding Logic in the Component Class

Open accordion.component.ts and define your FAQ data along with toggle functionality:

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

@Component({

selector: 'app-accordion',

templateUrl: './accordion.component.html',

styleUrls: ['./accordion.component.css']

})

export class AccordionComponent {

faqs = [

{ question: ‘What is Angular?’, answer: ‘Angular is a platform for building mobile and desktop web applications.’, open: false },

{ question: ‘How does data binding work?’, answer: ‘Data binding allows synchronization of data between the model and the view.’, open: false },

{ question: ‘What is a component?’, answer: ‘A component controls a patch of the screen called a view.’, open: false },

];

toggle(item: any) {

item.open = !item.open;

}

}

Adding Styles for Better Appearance

Open accordion.component.css and add some styles:

.accordion {

border: 1px solid #ccc;

border-radius: 4px;

overflow: hidden;

}

.accordion-header {

background-color: #f1f1f1;

cursor: pointer;

padding: 10px;

font-weight: bold;

}

.accordion-body {

padding: 10px;

background-color: #fff;

border-top: 1px solid #ccc;

}

Embedding the Accordion in Your App

Finally, include the app-accordion selector in your main template, typically in app.component.html:

<app-accordion></app-accordion>

Now, run your Angular app with ng serve and see your custom FAQ accordion in action!