[SalesForce] Can’t dynamically change Label of lightning:tab

I need to dynamically change the label of a lightning:tab — without reloading the entire tab. I thought I could do it with normal data binding, but it's not working.

<aura:attribute name="tabName" type="String" default="defaultName"/>

<lightning:tabset>
    <lightning:tab id="example" label="{!v.tabName}"/>

When this loads, it displays "defaultName" as the name of the tab, so it's pulling the data value. However, when the controller changes the value for tabName, the tab label doesn't update.

Controller code…

component.set("v.tabName", "AnotherName");

I have pasted in {!v.tabName} elsewhere on the page, and the value is changing, but the tab label doesn't update.

Are tab labels unable to change dynamically?

Best Answer

Not all components respond to changes to bound attributes. In this case, you need to force a rerender, usually done via aura:if:

<aura:application extends="force:slds">
    <aura:attribute name="tabName" type="String" default="defaultName"/>
    <aura:attribute name="showTabs" type="Boolean" default="true" />
    <aura:if isTrue="{!v.showTabs}">
    <lightning:tabset>
        <lightning:tab id="example" label="{!v.tabName}"/>
    </lightning:tabset>
    </aura:if>

    <ui:button label="Update" press="{!c.update}" />
</aura:application>

({
    update : function(component, event, helper) {
        component.set("v.showTabs", false);
        component.set("v.tabName", "New label");
        setTimeout($A.getCallback(() => component.set("v.showTabs", true)));
    }
})

As unfortunate as this is, whenever you encounter a situation like this, the only viable solution is to reconstruct the components later.

Related Topic