Configure a custom element by declaring which HTML attributes should trigger updates. observedAttributes limits attributeChangedCallback to changes the component actually needs. section 3.0 section 3.4
Declare observedAttributes as a static getter returning an array of attribute names. The browser calls attributeChangedCallback only when a changed attribute appears in that array. section 3.4
Use the pattern incrementally:
- Choose attributes whose changes should affect component behavior, such as searchterm or layout. section 3.4 section 7.3
- Return those names from the static observedAttributes getter; add more names as needed. section 3.4
- Handle the matching name inside attributeChangedCallback and update the component. section 3.4
Reacting to a layout attribute
static get observedAttributes() { return ['layout']; }\n\nattributeChangedCallback(name, oldvalue, newvalue) {\n this.innerHTML = '';\n const template = document.getElementById(newvalue);\n this.appendChild(template.content.cloneNode(true));\n}\n\nChanging <biz-card layout="none"> through a menu selects and renders the matching template. Initial attribute values also trigger the callback. section 7.3
Listing 7.7. Simplified business card example using templates to drive HTML and CSS
export default class BizCard extends HTMLElement {
static get observedAttributes() { return ['layout']; }
attributeChangedCallback( #1
name, oldvalue, newvalue) {
this.innerHTML = '';
const template = document.getElementById(newvalue);
const clone = template.content.cloneNode(true);
this.appendChild(clone);
}
}
if (!customElements.get('biz-card')) {
customElements.define('biz-card', BizCard);
}
Inspect the compact template-driven component that observes layout and swaps its rendered content. section 7.3
