Lightning Web Components – How to Set a Public Reactive Property During Component Construction

I'm reading about lwc properties and came across a statement.

A component that declares a public reactive property can’t set the property value, except at component construction time. A parent
component that uses the component in its markup can set the
component’s public property value. In our example, the c-todoitem
component can’t update the value of the itemName property in the
todoitem.js file.

Based on the above statement I can't set a public reactive property(@api), except for the component construction time. I know we can use getters and setters to set the value, but it does involve declaring a private reactive property(@track).

In this context what is the meaning of component construction time. Is there another way to set the value of public reactive properties in the declared component without the interference of the private reactive properties?

Best Answer

It simply means that you need to set the value in just one of two places. Both will be demonstrated here, as well as what's not:

export default class AppName extends LightningElement {
  @api message1 = 'Default message'; // allowed
  @api message2;
  constructor() {
    super(); // must be called, and must be called before using 'this'
    this.message2 = 'New default message'; // also allowed
  }
  onclickhandler() {
    this.message1 = 'Try to change on click...'; // not allowed
  }
}

Note that the constructor is always called constructor, unlike Java and other languages where the constructor is the class' name.


After defining it either inline or via constructor, you are no longer allowed to modify the property at all. It becomes read-only. If you want to be able to communicate to the parent component, the get/set combination is required.