Lightning Web Component Reflect JavaScript Properties as a HTML Attributes

Let’s understand here how we can able to set the HTML properties from the lightning web component properties which are almost similar like how you are setting HTML attributes using the createAttribute() method. You can control whether public JavaScript properties appear as attributes in the rendered HTML of a Lightning web component. Allowing properties to appear as attributes are especially important when creating accessible components because screen readers and other assistive technologies use HTML attributes. All HTML attributes are reactive by default. When an attribute’s value changes in the component HTML, the component is re-rendered.When you take control of an attribute by exposing it as public property, the attribute no longer appears in the HTML output by default. To pass the value through to the rendered HTML as an attribute (to reflect the property), define a getter and setter for the property and call the setAttribute() method. You can also perform operations in the setter. Use a private property to hold the computed value. Decorate the private property with @track to make the property reactive. If the property’s value changes, the component rerenders.


In this example, we will be seeing how to set the title to a component on mouseover.

Create a lightning web component using the below SFDX command.


Use the below mycomponent.html code


Use the below mycomponent.js code. This javascript controller title as public property. It converts the title to uppercase and uses the tracked property privateTitle to hold the computed value of the title. The setter calls setAttribute() to reflect the property’s value to the HTML attribute


Use the below mycomponent.js-meta.xml code



Create a new lightning web component using this SFDX command. we will be calling the my-component from this parent component.



Use this parent1.html code


Push the changes to scratch org and add the changes to page layout and you can able to see the title on mouseover as shown below.




To make sure that you understand how JavaScript properties reflect to HTML attributes, look at the same code without the call to setAttribute(). The generated HTML doesn’t include the title attribute. Now update the mycomponent.js as shown below.


update the mycomponent.js code  as shown below


Push the changes to scratch org. Now when you mouseover on the parent component you dnt see the title appears. Similarly, you can use removeAttribute() to hide HTML attributes from the rendered HTML.