[SalesForce] How to change Lightning:Tab label dynamically

I want to change label for tab dynamically, but that's not working.
Please find the related code below:

Component

<lightning:tab label="test1" id="tabId">

JS Controller

component.find("tabId").set('v.label', 'test2');

Can you help me with this?

Best Answer

UPDATE

It turns out that the label attribute in lightning:tab is of type component[] and not text. And thus it was not being set in the first place when trying to set the label directly.

component.find("tabId").set("v.label", "New Value");

So to set the label, you will need to get the label component and then set the value attribute on it. Note that you will need to use aura:id instead of id as mentioned in the docs.

This will yield you the results.

// this returns the tab's label component as an array
var tabLabel = component.find("tabId").get("v.label");

// this was to verify, where is the label's value set.
// the 0-th element in the label component has an attribute value
console.log(tabLabel[0].get("v.value")); 

// once you change it, your new label will be rendered righ away
tabLabel[0].set("v.value", "New Label");

OLD ANSWER

While not completely sure about your use case, but re-rendering the tab will achieve for what you are looking for.

On Component, declare attributes as below:

<aura:attribute name="tabLabel" type="String" default="Old Label" />
<aura:attribute name="hasLabelChanged" type="Boolean" default="true" />

Then, use it as below to render the tab:

<aura:if isTrue="{!v.hasLabelChanged}">
    <lightning:tab label="{!v.tabLabel}" aura:id="tabId">
        Tab Contents here !
    </lightning:tab>
</aura:if>

And then in your JS, doing something will let you change the label.

component.set("v.hasLabelChanged", false);
component.set("v.tabLabel", "New Label");
component.set("v.hasLabelChanged", true);
Related Topic