How to trigger PrimeNG Accordion Click programmatically in Angular 2.0?

荒凉一梦 提交于 2019-12-04 12:08:39

Why not just use the tabs-property of the accordion itself?

<p-accordion #accordion>
    <p-accordionTab header="Header Content">
         Body Content
    </p-accordionTab>
</p-accordion>

@ViewChild('accordion') accordion: Accordion;

closeAllAccordionTabs() {
    if(!isNullOrUndefined(this.accordion.tabs)){
        for(let tab of this.accordion.tabs) {
            if(tab.selected) tab.selected = false;
        }
    }
}

openAllAccordionTabs() {
    if(!isNullOrUndefined(this.accordion.tabs)){
        for(let tab of this.accordion.tabs) {
            if(!tab.selected) tab.selected = true;
        }
    }
}

I was able to get this working using the same approach as you but moving the template variable to an element inside a custom p-header, instead of on the p-accordion-Tab.

<p-accordionTab>
    <p-header>
        <span #header>
            Header Content
        </span>
    </p-header>
    Body Content
</p-accordionTab>

Their doc page has info on the bottom about using custom header content: https://www.primefaces.org/primeng/#/accordion

updated Martin Kronstad's answer for es6 w/ arrow functions:

  closeAllAccordionTabs() {
    if (this.accordion && this.accordion.tabs) {
      this.accordion.tabs.forEach(tab => tab.selected = false);
    }
  }

Here's an alternate method that doesn't require @ViewChild. Use this if your accordion is in an *ngIf and is only added to the DOM on certain conditions(In this case the @ViewChild is undefined and can't be set).

Use the activeIndex property:

<p-accordion [activeIndex]="openAccordion">

Put this variable in the component:

openAccordion = -1;

When you want to open the accordion set this.openAccordion to the index of the accordion tab you want to open. e.g.

this.openAccordion = 0;

or in a unit test as I'm using it:

fixture.componentInstance.openAccordion = 0;

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!