Run Code When a Component Is Created
constructor() method fires when a component instance is created. Don’t add attributes to the host element during construction. You can add attributes to the host element in any other lifecycle hook.
The constructor flows from parent to child.
These requirements from the HTML: Custom elements spec apply to the
- The first statement must be
super()with no parameters. This call establishes the correct prototype chain and value for
this. Always call
- Don’t use a
returnstatement inside the constructor body, unless it is a simple early-return (
- Don’t use the
- Don’t inspect the element's attributes and children, because they don’t exist yet.
- Don’t inspect the element’s public properties, because they’re set after the component is created.
You can add attributes to the host element during any stage of the component lifecycle other than construction.
This pattern isn't recommended, because it adds an attribute to the host element in the
To add an attribute to the host element, use the
connectedCallback() method instead.