Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to trigger PrimeNG Accordion Click programmatically in Angular 2.0?

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
like image 798
Dynamic Avatar asked Dec 07 '22 19:12

Dynamic


1 Answers

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;
        }
    }
}
like image 79
Martin Kronstad Avatar answered Dec 11 '22 09:12

Martin Kronstad