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

Populating Modal on open with jquery/javascript

I am trying to dynamically populate a Modal when it opens, but so far all my attempts using append have failed. Here is the code for my Modal: <div class="modal fade" id="ModalForAllUsers" tabindex="-1" role="dialog" aria-hidden="true"> <div ...

Wallaby.js - The async() test helper requires a Zone to function properly

This project is built with Angular 6.x and tests are conducted using Karma/Jasmine. I'm facing a challenge while using Wallaby where my tests run successfully outside of it, indicating a possible configuration issue. Specifically, when running tests ...

Executing an SQL delete query with a button click using a JavaScript function in PHP

I have created a setup with three essential files - index.html, database.php, and function.js. In database.php, there is a form generated containing a delete button that triggers the deletion SQL query when clicked. The primary objective is to present a ta ...

Looking for assistance with aligning an image in a <td> cell that doubles as a link?

How can I center a play icon in the middle of a td cell and make the entire content clickable as a link, including the background image? I've tried various methods but can't seem to get it right without breaking the alignment. Any suggestions wou ...

The utilization of 'new' is not allowed with an expression that does not have a call or construct signature in TypeScript

While searching for a solution, I stumbled upon this link which unfortunately did not provide the answer I was looking for: Cannot use 'new' with an expression whose type lacks a call or construct signature I am facing a similar issue. In my JavaS ...

The act of exporting an enum from a user-defined TypeScript path leads to the error message "Module not

I have set up a custom path as explained in this particular discussion. "baseUrl": ".", "paths": { "@library/*": [ "./src/myFolder/*" ], } Within this module, I am exporting an Enum. export enum EN ...

Struggles with closing dropdown menus

How can I modify my drop down menu so that the first drop box closes when a new link is clicked? Additionally, how do I ensure that the menu closes when clicking on a child item without refreshing the page (since the content is dynamically pulled from a ...

jquery accordion failing to display content

Upon navigating to my website and accessing the webpage featuring an accordion, the accordion successfully appears and hides after 1500ms as intended. However, when attempting to reveal the text by clicking on the headings, nothing happens. The heading sim ...

Executing a function to erase the stored value in local storage during an Angular unit test

Looking to verify whether the localStorage gets cleared when I execute my function. Component ngOnInit() { // Logging out when reaching login screen for login purposes this.authService.logout(); } authService logout() { // Removing logged i ...

Collapsible Rows in Material-UI Table seamlessly integrated with regular rows

While using material-ui v4, I encountered an issue where my collapsible row columns are not aligning properly with my regular columns. Below is a photo and the code snippet for reference. As you can see in the image, when I expand the Frozen Yogurt row, th ...

Update gulp configuration to integrate TypeScript into the build process

In the process of updating the build system for my Angular 1.5.8 application to support Typescript development, I encountered some challenges. After a complex experience with Grunt, I simplified the build process to only use Gulp and Browserify to generat ...

I am unable to utilize the outcome of a custom hook within a function or within an effect hook

I've developed a unique custom hook that retrieves a list of individuals File: persons.hooks.ts import {useEffect, useState} from "react"; import Person from "../../models/person/Person"; const usePersons = () => { const ...

Error encountered by Angular's Injector in the AppModule when attempting to access the HttpHandler component

I have been successfully running an app for the past few months with no issues. Now, I am exploring the idea of moving some common services into a library that can be utilized by other applications. For this project, I decided to avoid using Angular CLI t ...

I would like to add a border at the bottom of each item in a ul list

My current focus is on making my website responsive with a breakpoint set at 576px I am aiming to achieve the design shown in this image without any space in the border-bottom and have both elements expand to full width: menu li hover However, I'm c ...

Create a custom definition for the useSelector function within a separate TypeScript file in a React

Question: Is it possible to define a type like <TRootState, string> in an external file and use it directly inside multiple Component files? External file: export type TUser = <TRootState, string> // This method does not work Component's ...

Struggling with transferring a hidden form value from the database to a PHP if-statement

In my database table named "Related," I have 3 columns: related_id article_id object_id This table tracks the relationships between articles and objects. I recently updated the code to only include a delete button (x). When a user clicks on this button, ...

Internet Explorer fails to execute CSS or jQuery commands

Apologies in advance for posing a question that may not be specific or beneficial to the wider community. Currently, my main focus is resolving this issue for my own peace of mind. In the process of designing a website, I implemented a social drawer featu ...

In React TS, the function Window.webkitRequestAnimationFrame is not supported

I'm facing an issue where React TS is throwing an error for window.webkitRequestAnimationFrame and window.mozRequestAnimationFrame, assuming that I meant 'requestAnimationFrame'. Any suggestions on what to replace it with? App.tsx import Re ...

When combining <a> with the class line-through, the line does not appear

I am currently utilizing a class to replace the deprecated strike in HTML: .entfall { text-decoration: line-through; } However, when using Firefox 38.x and the following code: <span class="entfall"><a href="some link">text</a></span ...

The HTML code is displayed on the page as source code and is not run by the browser

Here is the code snippet I am using: $link = "<a class=\"openevent\" href=\"$finalUrl\" target=\"_blank\">Open Event</a>"; foreach ($spans as $span) { if ($span->getAttribute('class') == 'categor ...