Working with Conditional Attribute Defaults in Lightning

Setting defaults on attributes in lightning can be a useful tool when setting the initial state of components.

There is an 'undocumented feature' that allows us to set attribute defaults conditionally, but you may find that this does not work exactly as you would expect.

It turns out that setting a conditional default will 'lock' any changes to that attribute, as demonstrated below.

In this example we create two attributes 'myString' and 'mySimpleString'. Both attributes have default values but the default on 'myString' is wrapped in a condition.

We then trigger an init handler to update the value of both strings to be 'Set Directly' when the component is initialised.

The example shows that 'mySimpleString' will update to the new value, but 'myString' does not.


For additional complexity, setting a conditional default with an object reference will 'lock' any changes to that attribute, except from the object used in the condition.

In this example we add two attributes to the component: 'myObj', an object that begins without any values, and 'myObjString', a string with a conditional default that will set the value to 'Default Val' if the object is empty, otherwise it will default to myObj.val.

In the init handler we set the value of myObj.val to 'Set in Object' and also attempt to set the value of 'myObjString' directly.

The example shows that the direct set will fail, but the string will update to show the new value set on the object ('Set in Object').

It is worth noting that setting the default of myObjString to '{!v.myObj.val}' without the condition does allow direct updates, and those updates are also reflected in the object.

Comments

Popular posts from this blog

Handy Scripts for Salesforce Lightning Development

Detect URL Format (Lightning Experience)