1

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?

6
  • 1
    Can you elaborate on how it's not working? Any errors? Or is it simply not changing the label? Commented Dec 17, 2018 at 18:32
  • Yeah when I am trying to change the label using component.find(), its changing value to null. As we are using id instead of aura:id. Will that make any difference? Commented Dec 17, 2018 at 18:36
  • 1
    yes, component.find only works on aura:id, it does not work on the standard html id property Commented Dec 17, 2018 at 18:37
  • what about the id then? How can I change the value for label dynamically ? Commented Dec 17, 2018 at 18:38
  • 2
    @SankalpGupta as Sebastian said, use aura:id instead of id.
    – sfdcfox
    Commented Dec 17, 2018 at 18:42

1 Answer 1

3

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);
0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .