how to change p-tabPanel name when selected

Viewed 500

On my tabs, I used to have names too large. Then I set short names for each tab, but I want to show the full name when it's selected.

1 Answers

Without seeing your code, it's hard to make a solution fit for you. However, I think this should be able to help you on where to start. It's not the most efficient if you have a lot of headers, but I think it's a good start to help you.

We can use Angular's ng-template element with primeng's custom template header to create two elements which use *ngIf to decide when to show the long or the short header. Using the (onChange) event with $event in our function, we can detect the current tab and use this to pass a value to our activeTab variable.

Below I have set the default index of the p-tabPanel to 0 (and our activeTab.index to 0 too so it shows the long name on the first tab by default) which changes once you change the tab/index. The long tab header should be shown if the activeTab.index of the selected tab is equal to the tabIndex of p-tabView. If it is not equal, just show the shorter header.

HTML:

<p-tabView (onChange)="switchHeaders($event);" [(activeIndex)]="tabIndex">
    <p-tabPanel>
        <ng-template pTemplate="header">
            <div *ngIf="activeTab!==0"><span>Shortname</span></div>
            <div *ngIf="activeTab===0"><span>Really long header name</span></div>
        </ng-template>
    </p-tabPanel>
    <p-tabPanel>
        <ng-template pTemplate="header">
            <div *ngIf="activeTab!==1"><span>Shortname2</span></div>
            <div *ngIf="activeTab===1"><span>Really long header name2</span></div>
        </ng-template>
    </p-tabPanel>
    <p-tabPanel>
        <ng-template pTemplate="header">
            <div *ngIf="activeTab!==2"><span>Shortname3</span></div>
            <div *ngIf="activeTab===2"><span>Really long header name3</span></div>
        </ng-template>
    </p-tabPanel>
</p-tabView>

TS:

tabIndex = 0;
activeTab = 0;

switchHeaders(tabNumber: any) {
  this.activeTab = tabNumber.index;
}

Good luck!

Related