javaangulartypescriptprimengtabmenu

PrimeNG tabMenu click event to be disabled for disabled tabs


I have an issue with PrimeNG p-tabMenu for menu that are disabled.

Say for example I have a tabMenu with 4 sub tabs -> AAA, BBB, CCC, DDD.

This is how the menuItems are setup in the ts component.

//....

invDocs: InventoryDocs[] = [];
invMenu: InventoryDocs[] = [];
this.invMenu = this.data.cdMenu;
this.invDoc = this.data.cdDocs;
this.menuItems = []; 
if(this.invMenu != null && this.invMenu.length > 1){
    this.showMenu = true;
    for (let i = 0; i < this.invMenu.length; i++) {                  
        this.menuItems.push({label: this.invMenu[i].fileDescr, id:  this.invMenu[i].menuId, disabled: this.invMenu[i].subCount > 0});
        this.activeItem = this.menuItems[0];
    }
    this.currentPdf = this.invDoc.docBlob;
}
                
            


activateMenu(tab){ 
    console.log(tab);
    this.invDocId = tab.activeItem.id;
    this.showMenu = true;
    this.retriveCurrentPdf(this.invDocId);
}           
                
.....//

sample value pushed:

this.menuItems.push({lable: 'AAA', id: 1, disabled: false});
this.menuItems.push({lable: 'BBB', id: 1, disabled: true});
this.menuItems.push({lable: 'CCC', id: 1, disabled: true});
this.menuItems.push({lable: 'DDD', id: 1, disabled: false});

By default 'AAA' is set to active.

my component html looks as follows:

<div style="width: 3em;">
       <p-tabMenu #tab [model]="menuItems" [activeItem]="activeItem" (click)="activateMenu(tab)" class="customWrapper" ></p-tabMenu> 
</div> 

The page is rendered with 4 tabs where AAA and DDD are enabled and BBB, CCC are disabled. The click event on the tab calls the activateMenu method and displays diff pdf in the UI.

The issue is with this click event which is getting triggered for the disabled buttons too. Even though tabs BBB, CCC are disabled, it lets me click the tab but the activeItem in the tab# is retained of what was previously active so I cannot stop the event propagating. Say when the page loads it defaults to AAA tab. Now even though BBB is disable it lets me click the tab 'BBB' and when I print the console.log in activateMenu() the activeItem in label and id shows that of tab AAA. Can someone suggest me how to prevent the click for disabled tabs please?


Solution

  • I think you should rather use command function wich is part of MenuItem. This function will be triggered on click only if tab is not disabled.

    this.items = [
      {
        label: "Home",
        icon: "pi pi-fw pi-home",
        command: event => {
          this.activateMenu(event);
        }
      },
      {
        label: "Edit",
        icon: "pi pi-fw pi-pencil",
        disabled: true,
        command: event => {
          this.activateMenu(event); // this one won't be triggered because tab is disabled
        }
      }
    ]
    
    activateMenu(event) {
        console.log("click on " + event.item.label + " tab!");
    }
    

    See demo