<p-tabView [controlClose]="true">
<p-tabPanel *ngFor="let tab of tabs"
[header]="tab.actionName"
(click)="selectTab(tab)"
[selected]="tab.selected"
(onClose) = "close(tab)"
[closable]="tab.closable">
</p-tabPanel>
</p-tabView>
<ng-container *ngIf="selectedTab">
<ng-container *ngComponentOutlet="selectedTab.actionComponent; inputs: selectedTab.inputs"></ng-container>
</ng-container>
i want to call a funtion to perform some action whenever i close some tab, unfortunately the onclose is not working on p-tabPanel
I recently faced the same issue, the problem is the (onClose) does not work on p-tabPanel, it works on p-tabView only so we need to use the (onClose) on p-tabView only and pass an Event the event gives the index of tab to be removed and then we can remove the tab in our .ts code, i am providing code snippet below for better understanding
<p-tabView (onClose)="onTabClose($event)" [controlClose]="true">
<p-tabPanel *ngFor="let tab of tabs; let i = index"
[header]="tab.title"
[closable]="true">
<!-- Tab Content -->
<ng-container *ngIf="selectedTab === tab">
<!-- Display content for the selected tab -->
</ng-container>
</p-tabPanel>
</p-tabView>`
import { Component, OnInit } from '@angular/core';
import { TabViewCloseEvent } from 'primeng/tabview';
@Component({
selector: 'app-tab-example',
templateUrl: './tab-example.component.html',
styleUrls: ['./tab-example.component.css']
})
export class TabExampleComponent implements OnInit {
tabs = [
{ title: 'Tab 1', content: 'Content 1' },
{ title: 'Tab 2', content: 'Content 2' },
{ title: 'Tab 3', content: 'Content 3' }
];
selectedTab = this.tabs[0]; // Initially select the first tab
ngOnInit(): void {}
onTabClose(event: TabViewCloseEvent) {
const index = event.index; // Get the index of the tab to close
this.tabs.splice(index, 1); // Remove the tab from the list
// Select a new tab if the closed tab was the selected one
if (this.selectedTab === this.tabs[index]) {
this.selectedTab = this.tabs.length ? this.tabs[0] : null; // Select a new tab or clear selection
}
}
}
In PrimeNG, when you click the close icon on a tab (using p-tabPanel inside p-tabView), the following happens:
The onClose event is triggered.
The event provides information about which tab was clicked.
You handle the event by removing the tab from the list of tabs.
The p-tabView component updates the UI to reflect the removal of the tab.
This process allows users to dynamically close tabs, and the p-tabView component ensures the view remains consistent with the updated list of tabs.
Hope, this helps!!
Keshav Vats is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.