What steps can I take to troubleshoot and repair my accordion feature within an Angular project?

As a newcomer to Angular, I recently attempted to create an accordion component but encountered unexpected behavior. Here is the HTML code for my attempt:

 <div class="faq-item-container">
      <h1 class="mt-1 mb-5"><strong>Frequently Asked Questions</strong></h1>
    <div class="row" (click)="toggleDetail(); toggleIcon();" *ngFor= "let faq of faqs">
      <div class="col my-2">
        <h3> {{faq.title}} <a><fa-icon [icon]="faChevronDown" class="float-right"></fa-icon></a></h3>
      </div>
      <div class="col-12" *ngIf="showDetail">
        <div class="faq-detail-container mt-1">
          <div class="col-12">
            <p><small>
              {{faq.content}}
            </small></p>
        </div>
      </div>
    </div>
  </div>
</div>

And here is the corresponding TypeScript code:

import { Component, OnInit } from '@angular/core';
import {faChevronUp, faChevronDown, IconDefinition, faSquare} from '@fortawesome/free-solid-svg-icons';

@Component({
  selector: 'app-jobs-faq',
  templateUrl: './jobs-faq.component.html',
  styleUrls: ['./jobs-faq.component.scss']
})
export class JobsFaqComponent implements OnInit {
  faChevronUp: IconDefinition = faChevronUp;
  faChevronDown: IconDefinition = faChevronDown;


  showDetail: boolean;
  faqs = [
    {
      id: 1,
      title: 'faq1',
      content: 'content1'
    },
    {
      id: 2,
      title: 'faq2',
      content: 'content2'
    },
    {
      id: 3,
      title: 'faq3',
      content: 'content3'
    }
  ];


  constructor() {
    this.showDetail = false;
   }


  toggleDetail(): void {
    this.showDetail = !this.showDetail;
  }
  toggleIcon() {
    if (this.faChevronDown === faChevronDown) {
        this.faChevronDown = faChevronUp;
    } else {
        this.faChevronDown = faChevronDown;
    }
}

  ngOnInit() {
  }

}

The issue arises when clicking on "faq1" causing the other items to collapse as well. This is due to calling the same function. How can I modify my code to individually trigger each item in the accordion and prevent them from collapsing together? Your assistance is greatly appreciated. Thank you.

Answer №1

If you're looking to expand only one section at a time or keep others closed when one is clicked, consider implementing this approach:

<div class="faq-item-container">
      <h1 class="mt-1 mb-5"><strong>Frequently Asked Questions</strong></h1>
    <div class="row" (click)="toggleDetail(faq.id); toggleIcon();" *ngFor= "let faq of faqs">
      <div class="col my-2">
        <h3> {{faq.title}} <a><fa-icon [icon]="faChevronDown" class="float-right"></fa-icon></a></h3>
      </div>
      <div class="col-12" *ngIf="faq.showDetail">
        <div class="faq-detail-container mt-1">
          <div class="col-12">
            <p><small>
              {{faq.content}}
            </small></p>
        </div>
      </div>
    </div>
  </div>
</div>
import { Component, OnInit } from '@angular/core';
import {faChevronUp, faChevronDown, IconDefinition, faSquare} from '@fortawesome/free-solid-svg-icons';

@Component({
  selector: 'app-jobs-faq',
  templateUrl: './jobs-faq.component.html',
  styleUrls: ['./jobs-faq.component.scss']
})
export class JobsFaqComponent implements OnInit {
  faChevronUp: IconDefinition = faChevronUp;
  faChevronDown: IconDefinition = faChevronDown;

  faqs = [
    {
      id: 1,
      title: 'faq1',
      content: 'content1',
      showDetail: false
    },
    {
      id: 2,
      title: 'faq2',
      content: 'content2',
      showDetail: false
    },
    {
      id: 3,
      title: 'faq3',
      content: 'content3',
      showDetail: false
    }
  ];

  toggleDetail(faqId: number): void {
    this.faqs = this.faqs.map(faq => {
        faq.showDetail = (faq.id == faqId) ? !faq.showDetail : false;
        return faq;
    });
  }

  toggleIcon() {
    if (this.faChevronDown === faChevronDown) {
        this.faChevronDown = faChevronUp;
    } else {
        this.faChevronDown = faChevronDown;
    }
  }

  ngOnInit() {
  }

}

Keep in mind that your [icon]="faChevronDown" should be dependent on the faq within the scope of your *ngFor directive. You can practice and explore ways to address this, such as using a ternary operation based on faq.showDetail.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Distributing elements evenly across the parent width using Angular FlexLayout for a responsive design

I need to create 3 div squares: div-left, div-middle, and div-right, each with a width of 300px. These squares should be arranged horizontally within the parent div main-section, which will adjust its size based on the screen width, being 1300px if the scr ...

Tips for allowing a position:absolute <div> to expand as though it were containing a lengthy <p>innerText

This div automatically adjusts its width to fit the content inside, even if it extends beyond the page boundaries. Is there a way to make this div expand to fill the entire width of the page without needing a paragraph? <div style="position:absolute;le ...

WordPress Migration Causing Issues with Custom Font Display

I recently moved my website from to using the Duplicator plugin, but I'm facing an issue with the custom font 'Kanit' not displaying correctly. I have double-checked on the backend and confirmed that Kanit font is properly set up. Below i ...

Encountering a timeout error when trying to test the video element with Jest

My function extracts meta data such as width and height from a video element in the following code snippet: export async function getVideoMetadata( videoBlobUrl: string, videoElement: HTMLVideoElement, ): Promise<{ width: number; height: number }> ...

How to correct placeholder text display in the input of a Material UI text field

Currently, I am utilizing the material ui text field component. The issue at hand is that when the text field is in focus, the placeholder shifts to the top of the field. https://i.stack.imgur.com/P5flf.png I prefer for the placeholder to remain within ...

The JQuery Datepicker function consistently returns a null value when attempting to retrieve the selected date

I've encountered a challenge while working on a project recently. Currently, I'm utilizing Spring 3.0 with its integrated validation alongside Hibernate 3.6. My goal is to implement a JQuery datepicker for users to input dates. However, the dat ...

What's the best way to add animation to the send icon while hovering over the button?

<div class="text-center"> <button [disabled]="btnStatus" class="btn btn-secondary buttonSend" type="submit"> <div [hidden]="btnStatus"> Send Message&nbsp;&nbs ...

Chrome method for creating Flexbox columns of equal height

I am implementing a simple 2-column layout and I want to utilize Flexbox to ensure equal heights for the columns: HTML <div class="row flex"> <!-- menu --> <div class="col-xs-4"> <aside> Menu content wi ...

Tips for extracting the chosen value from a dropdown list within a table cell using JavaScript

Here is an example of an HTML element: <td> <select> <option value="Polygon 47">Polygon 47</option> <option value="Polygon 49">Polygon 49</option> </select> </td> I am looking for a ...

Creating a rotating circle in CSS with ion-slides: A step-by-step guide

Hello, I am attempting to develop a circular object that will rotate in the direction it is dragged. Within this circle, there are elements positioned along the border so that these elements also spin accordingly. To illustrate, below are the specific elem ...

Ensure that both tables contain columns of equal size

I am facing a challenge with 2 HTML tables that are positioned directly on top of each other. Each table has the same number of columns, however, the text within them may vary. Additionally, both tables can consist of multiple rows. My goal is to ensure th ...

What steps can I take to ensure that the elements are in the same row instead of being displayed in three separate rows?

(I'm a beginner in web development and need some help) Is there a way to align elements into the same row instead of stacking them up in separate rows? I'm working on creating a header bar similar to the one on the Naive UI Documentation Website. ...

Modify the view to display the router outlet as a sidebar

Hello, I am trying to figure out why I am unable to access a child route in my application. I have a sidebar where I want to display a list, and if I want to add or edit an item, I would like the view to change within the sidebar from the list to a form a ...

Using div tags as interactive buttons, as well as incorporating dynamic functionality such as delete and report spam options

In this practice test scenario, the objective is to log in to Gmail, click on all checkboxes in a dynamic web table, and delete the mails. Below is the code that I have created for this task. The issue arises when checking if the delete button is visible. ...

Having trouble with the Tailwind transition in my Next.js component

I'm facing an issue with the ease out transition not working as expected. I need the side to slide in from left to right with a duration of 500ms. Despite trying various solutions, I can't seem to figure out why it's not functioning properly ...

Steps to reset an Angular material toggle button:1. Locate the

<div id="slider-group" *ngFor="let sliderToggle of sliderToggleGroup"> <div> <mat-slide-toggle (ngModelChange)="updateSlider($event,sliderToggle)" [(ngModel)]="sliderToggle.isChecked"> {{sliderToggle.na ...

Deleting various classes (jQuery)

Is there a more effective alternative to rewriting the following code snippet? $('element').removeClass('class1').removeClass('class2'); I am unable to utilize removeClass(); because it would eliminate ALL classes, and that ...

Comparing functions and function issues when using onClick in JavaScript

I have successfully created an Image Element on my web page dynamically using JavaScript. I am now trying to set an onClick event for the newly created image element. However, I am encountering a problem and I cannot figure out why?, This is the code I ...

When attempting to access http://localhost:3000/traceur in Angular 2 with the angular-in-memory-web-api, a 404 (Not Found) error

Hello, I'm encountering an issue with angular-in-memory-web-api. I have attempted to use angular2-in-memory-web-api in SystemJS and other solutions, but without success. I am currently using the official quickstart template. Thank you for any assistan ...

Convert a relative path to an absolute path using the file:// protocol

When I scrape a website with similar html content, I come across the following code: <a href="/pages/1></a> In addition to this, I have access to the window.location object which contains: origin:"http://www.example.org" This allows me to ...