TypeScript (Developer Preview)
constructor()
connectedCallback() and disconnectedCallback()
renderedCallback()
render()
errorCallback()
Mobile-Ready Components
Develop Secure Code
The 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, which means that it fires in the parent first. You can’t access child elements because they don’t exist yet. Properties aren’t passed yet, either. Properties are assigned to the component after construction and before the connectedCallback() hook.
These requirements from the HTML: Custom elements spec apply to the constructor().
super() with no parameters. This call establishes the correct prototype chain and value for this. Always call super() before touching this.return statement inside the constructor body, unless it is a simple early-return (return or return this).document.write() or document.open() methods.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 constructor().
1// don't do this
2import { LightningElement } from "lwc";
3export default class Deprecated extends LightningElement {
4 constructor() {
5 super();
6 this.classList.add("new-class");
7 }
8}To add an attribute to the host element, use the connectedCallback() method instead.
1import { LightningElement } from "lwc";
2
3export default class New extends LightningElement {
4 connectedCallback() {
5 this.classList.add("new-class");
6 }
7}See Also