Reflect JavaScript Properties to HTML Attributes
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 is 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 rerendered.
To enable a screen reader to read a value aloud to the user, use @api
to expose a public title
attribute.
When you take control of an attribute by exposing it as a public property, the attribute doesn't appear 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 field to hold the computed value.
This example exposes title
as a public property. It converts the title to uppercase and uses the property _privateTitle
to hold the computed value of the title. The setter calls setAttribute()
to reflect the property’s value to the HTML attribute.
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.
Before you set a value, check if the value has already been set by the consumer.
Setting the tabindex
using this.setAttribute()
results in this markup.
To set and get these attributes, use setAttribute()
and getAttribute()
.
for
aria-activedescendant
aria-controls
aria-describedby
aria-details
aria-errormessage
aria-flowto
aria-labelledby
aria-owns
To hide HTML attributes from the rendered HTML, call removeAttribute()
.
See Also