[SalesForce] Are global attributes possible in lightning component

It is possible to create attribute as global, I mean that attribute can be get & set in any lightning component or can we set the parent component attributes?

Best Answer

There are couple ways to handle this

1.Approach 1 involves using a static resource file to store all the global values

Here is how a code in your static resource look like

(function(w){
  "use strict"; //Optional because LC on LockerService active runs in strict mode

  var globalConstants = {
    "variable1":"abc",
    "variable2":"zyz"
  };

  w.globalvalues = globalConstants;

})(window);

And then in lightning component you will use like below

  ltng:require scripts="{!$Resource.TestScript}" afterScriptsLoaded="{!c.afterScriptsLoaded}" />
   <ui:button label="Do job" press="{!c.populateConstants}"/>

The controller

populateConstants : function(cmp){
  globalvalues.variable1; 
  globalvalues.variable2; 
}

Note you can use this on all init handler to load this data

2.Use an attribute in Parent component and then trickle down the attribute in all the components like below

<attribute name="constant" type="String" default="Hello"/>

The child will have similar attribute and you will call like below

<c:childcomponent constant="{!v.constant}"/>
Related Topic