Switch on ngbAccordion via TypeScript File

I need to implement a function in my component.ts file that will toggle the accordion using a button. Can you help me with the script for this?

This is my HTML code:

<button (click)="toggleAcc()" type="button" class="btn btn-primary">Primary</button>
    <ngb-accordion id="acc1" #acc="ngbAccordion" activeIds="ngb-panel-0">
                <ngb-panel id="detailAcc">
                    <ng-template ngbPanelTitle>
                        <span>&#9733; <b>Fancy</b> title &#9733;</span>
                    </ng-template>
                    <ng-template ngbPanelContent>
                       Hello World!!!!
                    </ng-template>
                </ngb-panel>
            </ngb-accordion>

I am looking for a script for the toggleAcc method

@Component({
  selector: 'my-component',
  templateUrl: './my-component.html'
})

toggleAcc(){
     **********Need code here to toggle the accordion*********
}

I am using Angular 14, Bootstrap 5, and ng-bootstrap12

Answer №1

Method 1: Providing panel ID and toggling.

import { Component, ViewChild } from '@angular/core';
import { NgbAccordion } from '@ng-bootstrap/ng-bootstrap';

@ViewChild('acc') acc: NgbAccordion;

toggleAccordion() {
  this.acc.toggle('detailAcc');
}

Method 2: Loop through the 'panels' array to toggle each panel.

import { Component, ViewChild } from '@angular/core';
import { NgbAccordion } from '@ng-bootstrap/ng-bootstrap';

@ViewChild('acc') acc: NgbAccordion;

toggleAccordion() {
  for (let panelId of this.acc.panels.map((x) => x.id)) {
    this.acc.toggle(panelId);
  }
}

View Sample StackBlitz Demo

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

Looking to adjust the API response to fit the necessary JSON format for an Angular project?

A modification is needed in the API response to align with the required JSON format provided below. The current responses and the desired format are detailed for reference. Assistance is appreciated. The current representation of individual's data ne ...

Tips for troubleshooting or modifying a dependency that exclusively consists of type declaration files

I am currently facing a challenge where I need to access and debug/change the code of one of our dependencies that contains custom Angular components from a separate repository. This particular repository is being included via a self-hosted npm registry wi ...

Angular: Display or Conceal button when hovering over a div

I am working on a small Angular project that involves displaying a list of cars after performing a search action in the database. I am looking to implement a feature where, when a user hovers over the <div class="about">, a button (<button class=" ...

Encountering an error of ExpressionChangedAfterItHasBeenCheckedError while trying to refresh the

I'm encountering an issue that I need help with: https://i.stack.imgur.com/4M54x.png whenever I attempt to update the view using *ngIf to toggle on an icon display. This is what my .ts file looks like: @Component({ selector: 'app-orders&ap ...

Updating a boolean value and passing a body to an Angular HttpClient PUT request

Need help with passing a model in an API Put Request. Also, seeking guidance on including a boolean value concurrently. https://i.sstatic.net/fvjtK.png ...

How to Insert a New User into the Database Using Angularfire2

During the login process, I implemented the following method: login() { this.auth.login(); this.authService.login().subscribe(() => { if (this.authService.isLoggedIn) { console.log("ADDING THE USER.."); // Insert a new user into the use ...

Is it possible for an uninitialized field of a non-null literal string type to remain undefined even with strict null checks in

It seems that there might be a bug in Typescript regarding the behavior described below. I have submitted an issue on GitHub to address this problem, and you can find it at this link. The code example provided in that issue explains the situation more clea ...

The type 'undefined' cannot be assigned to the type 'string | Buffer | { key: string | Buffer; passphrase: string; } | GetPublicKeyOrSecret'

Verification Code for JWT This function is used to verify a jwt using typescript. public verify( token: string, secretOrPublicKey?: string | Buffer, options?: jwt.VerifyOptions ): Promise<object | string> { if (!secretOrPublicKey) { ...

Dealing with Uncaught Promises in Angular 2 while injecting a service

I followed the instructions in the official tutorial to start a project, but I'm encountering an issue with injecting services into my Angular2 app. Everything was working fine until I added a service. Here are the files : app.component.ts import ...

Issue with Angular 2 NgFor Pattern Error Message Display Absence

I am attempting to incorporate inputs with a regex requirement within an ngFor loop, but I am not receiving the expected error message when entering something that does not match the required pattern. Even when I input an incorrect pattern, "Test" remains ...

I'm having trouble getting Remix.run and Chart.js to cooperate, can anyone offer some guidance?

I've encountered a challenge with Remix.run and chart.js (react-chartjs-2) when attempting to display the chart. I followed the documentation and installed the necessary dependencies: react-chartjs-2 and chart.js. Here's the snippet from my pac ...

Having trouble retrieving data from a JSON file within an Angular application when utilizing Angular services

This JSON file contains information about various moods and music playlists. {mood: [ { "id":"1", "text": "Annoyed", "cols": 1, "rows": 2, "color": "lightgree ...

Update ngModel value following the PUT request response

I currently have a variable named dummy_value and I would like to update it using an input box. <p>{{dummy_value}}</p> <input [(ngModel)]="dummy_value" /> Upon making this change, the dummy_value updates instantly due to the two-way bin ...

Tips for seamlessly embedding Youtube iframes within Angular2 components. Resolving issues with unsafe value errors

ERROR: There seems to be an issue in the ./HomeComponent class HomeComponent - inline template:23:84. It is caused by using an unsafe value in a resource URL context. About my homeData model { id: 1, title: '2017 Super Bowl', graphic: 'ht ...

Is there a way to choose multiple IDs in this code that all share a common word?

I'm attempting to target several duplicate ids such as "img1, img2" in my code, but I haven't had any success. How can I select all the ids that contain the same word without relying on jQuery or any other external libraries? Below is the code s ...

Iterate and combine a list of HTTP observables using Typescript

I have a collection of properties that need to be included in a larger mergeMap operation. this.customFeedsService.postNewSocialMediaFeed(this.newFeed) .mergeMap( newFeed => this.customFeedsService.postFeedProperties( newFeed.Id, this.feedP ...

Guide on transforming a Unix timestamp into either "2000-01-01" or "2000-05-24 20:00:00" format, or the opposite way, using Deno

Just starting out with Deno and looking to convert a Unix timestamp such as 1646245390158 into either the format of 2000-01-01 or 2000-05-24 20:00:00, or vice versa. Any tips on how to achieve this? ...

Has anyone tried integrating Reveal JS with Angular 8?

Encountering a problem with the integration of Reveal JS in an Angular component. Despite being initialized after DOM processing, it is not displaying anything. What is the appropriate time to initialize the reveal library? Is there a way to incorporate ...

What is the most effective way to conceal an element in Angular 4 by utilizing *ng-if?

Testing the functionality of @Input in angular 2 which can hide or show a p tag. I am looking to test this feature using jasmine. Below is my component: import { Component,Input } from '@angular/core'; @Component({ selector: 'my-app&apo ...

The module "jquery" in jspm, jQuery, TypeScript does not have a default export

Having some trouble setting up a web app with TypeScript and jspm & system.js for module loading. Progress is slow. After installing jspm and adding jQuery: jspm install jquery And the initial setup: <script src="jspm_packages/system.js"></scri ...