Learn More: Web Components - MDN

Adding Attributes

Once you have a custom element defined, you can configure it to respond to attributes. The observedAttributes static property on your class specifies which attributes you want to respond to. The attributeChangedCallback method is called whenever an observed attribute changes. The method will also be called when the element is first created with an initial value.

Exposing Properties

A nice-to-have for any web component is for the attributes to be exposed as properties on the element. Often this just gets/sets a string, but sometimes you want to expose it as a number or boolean. This is simply a matter of defining getters/setters as you normally would on the class. Because the properties are reading and writing to the attribute values, the attributeChangedCallback is called. If you want to ensure a property always has a valid value, you can add validation logic to the attributeChangedCallback callback and it will trigger whether the attribute is set by code, or set in the document.