cannot access accordion properties in component .ts file in angular using ng-bootstrap angular 17

154 Views Asked by At

I am trying to follow the documentation to access the members of an accordion from my template in my component.ts file. I'm having trouble finding out how they are accessing the members. I can't seem to get access to them. I've tried injection and @ViewChild but I can't seem to access the properties.

This is the documentation snippet I am talking about:

If you want to work with the accordion API, you can get either accordion or item instances from the template.

<div ngbAccordion #accordion="NgbAccordion">
 <div ngbAccordionItem="first" #first="ngbAccordionItem" [collapsed]="false"> ... </div>
</div>
accordion.toggle('first');  // toggle the first item
accordion.closeAll();       // close all items

first.toggle();             // toggle the first item
first.collapsed;            // true if collapsed
first.collapsed = true;     // collapse the first item
first.disabled;             // true if disabled
first.disabled = true;      // disable the first item
first.id;                   // 'first'

If an item id is not provided as in the example above, it will be generated automatically in the 'ngb-accordion-item-XXX' format.

When trying to use something like first.toggle() it doesn't exist for me.

1

There are 1 best solutions below

0
TheCell On

The documentation is a bit vague on this. Here is how I got it working.

The Html Template component.html:

<div ngbAccordion>
  <div ngbAccordionItem>
    <div ngbAccordionHeader>
      <button ngbAccordionButton>Title</button>
    </div>
    <div ngbAccordionCollapse>
      <div ngbAccordionBody>
        <ng-template>
          <ng-content></ng-content> or just your content
        </ng-template>
      </div>
    </div>
  </div>
</div>

The Typescript file component.ts:

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

@Component({
  selector: 'app-accordion',
  templateUrl: './accordion.component.html'
})
export class AccordionComponent implements AfterViewInit {
  @ViewChild(NgbAccordionDirective) private accordion: NgbAccordionDirective;
  @ViewChild(NgbAccordionItem) private accordionItem: NgbAccordionItem;

  public ngAfterViewInit(): void {
    this.accordion.collapseAll();
    this.accordionItem.toggle();
    console.log(this.accordionItem.id); //ngb-accordion-item-0
  }
}