How to create separate close-able tab dynamically using Devextreme

|
| By Webner

Devextreme UI

The Devextreme provides a strong feature for the UI, you could change your UI appearance in an easy and simple way. You can also set the records whatever you want to show in the UI at run-time.

In the example, I will show how to create a separate close-able tab at runtime using Devextreme TabPanel.
Ex:
devextreme

If you click the hyperlink a new close-able tab will be open. If you click the close icon, the tab will be close as you can see the image.
For that, I have created the TabPanel in the div with id(”indexFileTabPanels”). I fixed the first title Item with “Users” in the tabPanelItemsTest variable. And another TabPanel Title is created dynamically when you click the hyperlink.
The sample code is here:

Html code:

<div id=”indexFileTabPanels”></div>

Jquery code :
/* tabPanelItemsTest is an array of items for dxTabPanel items which is dynamic in nature ( i.e. items can added/removed at runtime ) which represents the concept of close-able tabs */
var tabPanelItemsTest = [
{
title: "Users",
},
];
// In this , first tab item with “Users” title is taken as fixed and is not closeable
var tabPanelInstance;
//Code for generating devextreme tabPanel element
$(function ()
tabPanelInstance = $("#indexFileTabPanels").dxTabPanel({
items: tabPanelItemsTest,
repaintChangesOnly: true,
height: 450,
//The itemTitleTemplate configuration is used to append the title to the tab
// and add a close button.
itemTitleTemplate: function (itemData, itemIndex, itemElement) {
alert('itemData ' + itemIndex)
itemElement.append("<span>" + fileName + "</span>");
if (itemIndex >= 1) {
var titleCloseButton = $("<div class='tab-close' id='" + buttonId+"'>").dxButton({
type: "normal",
icon: "close",
hint: "Close",
onClick: function (e) {
// Code for removing the tab from tab panel on close button click
for (i = 0; i < tabPanelItemsTest.length; i++) {
if (e.element[0].id == tabPanelItems[i]) {
tabPanelItems.splice(i, 1);
tabPanelInstance.option("items", tabPanelItems);
break;
}
}
if (tabPanelItems.length == 0) {
tabPanelInstance.option("selectedIndex", 0);
}
}
});
itemElement.append(titleCloseButton);
}
},
}).dxTabPanel("instance");
});
// Below method is used to dynamically creating new tab by adding new item in the // itemssource array(“tabPanelItems”) of tabpanel
function insertNewTabTest(<yourTitleName>) {
let item = {
title: <yourTitleName>
};
tabPanelItems.push(item);
if (typeof (tabPanelInstance) !== "undefined") {
tabPanelInstance.option("items", tabPanelItems);
tabPanelInstance.option("selectedIndex", tabPanelItems.length - 1);
}
else
console.log(" undefined ");
}

Leave a Reply

Your email address will not be published. Required fields are marked *