How to trigger PrimeNG Accordion Click programmati

2019-04-13 07:45发布

I have an accordion as shown below.

When the link is clicked, I'd need to trigger the click event of all p-accordianTab elements.

How is it possible?

<a (click)="openCloseAll()" >{{openCloseAllText}} all</a>
                <p-accordion [multiple]="true">
                    <div class="row" *ngFor="let category of result.Categories">                        

                            <p-accordionTab #accordianTab header="{{category.Name}}">

                            </p-accordionTab>                       

                    </div>
                </p-accordion>

I tried adding this "#accordionTab" to the element and accessing it from TypeScript but doesn't work:

@ViewChild('accordionTab') accordionTab: ElementRef;
 openCloseAllText: string = "Open";
 openCloseAll() {
        // get all accordions and click them
        this.openCloseAllText = this.openCloseAllText === "Open" ? "Close" : "Open";
        this.accordionTab.nativeElement.click();
    }

TypeError: Cannot read property 'nativeElement' of undefined

3条回答
forever°为你锁心
2楼-- · 2019-04-13 08:08

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;
        }
    }
}
查看更多
神经病院院长
3楼-- · 2019-04-13 08:20

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

查看更多
Lonely孤独者°
4楼-- · 2019-04-13 08:28

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);
    }
  }
查看更多
登录 后发表回答