Search code examples
angulartypescriptprimengaccordion

PrimeNG: how to call accordion header name & collapse it from angular component.ts


I want to call accordion tab header's name in component.ts to collapse it by some condition. i want to add that function ngOnInit.

I've tried call some method from API documentation from PrimeNG but it's not working.

<p-accordion>
    <p-accordionTab header="Header 1">
       Content 1
    </p-accordionTab>
    <p-accordionTab header="Header 2">
        Content 2
    </p-accordionTab>
    <p-accordionTab header="Header 3">
        Content 3    
    </p-accordionTab>
</p-accordion>

https://primeng.org/accordion


Solution

  • If you want to change the selected tab or toggle the tab dynamically in PrimeNG's p-accordion component, you can follow these steps:

    1- Add a template reference #accordion to the p-accordion component in your HTML template:

    <p-accordion #accordion>
        <p-accordionTab header="Header 1">
           Content 1
        </p-accordionTab>
        <p-accordionTab header="Header 2">
            Content 2
        </p-accordionTab>
        <p-accordionTab header="Header 3">
            Content 3    
        </p-accordionTab>
    </p-accordion>
    

    2- In your component class, implement the AfterViewInit lifecycle hook:

    3- Add @ViewChild for #accordion template ref:

      @ViewChild('accordion') accordion: Accordion;
    

    4- Inside the ngAfterViewInit() method, you can evaluate your condition and set the selected property of the desired tab to true. Replace this.condition with your actual condition, and indexOfTab with the index of the tab you want to select or toggle.

      ngAfterViewInit(): void {
        if (this.condition) {
          this.accordion.tabs[indexOfTab].selected = true;
          //OR
          this.accordion.tabs[indexOfTab].toggle(indexOfTab);
    
    
        }
      }