lwc
lwc copied to clipboard
Components do not respect observedAttributes/attributeChangedCallback
Description
LWC components do not respect observedAttributes
or attributeChangedCallback
. attributeChangedCallback
is never called.
Create an LWC component:
import { LightningElement, api } from 'lwc'
export default class extends LightningElement {
static observedAttributes = ['foo']
@api changes = []
attributeChangedCallback(name, oldValue, newValue) {
this.changes.push({ name, oldValue, newValue })
}
}
The attributes are never observed:
const elm = createElement('x-observes', { is: Observes })
document.body.appendChild(elm)
elm.setAttribute('foo', 'bar')
elm.removeAttribute('foo')
// attributeChangedCallback never called
console.log(elm.changes) // []
Steps to Reproduce
Repro (look in the console)
Expected Results
Attributes are observed
Actual Results
Attributes are not observed
Possible Solution
Use properties and @track
instead of attributes
This issue has been linked to a new work item: W-11534181
CustomElementConstructor
seems to work similarly, but slightly differently:
-
static observedAttributes
is ignored – only the@api
props are considered -
attributeChangedCallback
is also ignored - However, the framework registers an
attributeChangedCallback
to decide when to set a prop:
https://github.com/salesforce/lwc/blob/acc19c692f57ed8405a10a09b77f174ea015e440/packages/%40lwc/engine-core/src/framework/base-bridge-element.ts#L84-L114