Javascript properties in lightning web component
In lightning web components we have two types of properties those are
- Private and Reactive Properties
- Public Properties
- Getter
Private and Reactive Properties:-
Private properties are only accessible in the component it is declared. It is declared using only identifier name. We don’t have to provide any keyword for datatype. We can also assign a default value to Private property.
Syntax for declaring Private Properties:
import { LightningElement } from 'lwc' ; export default class LwcComp extends LightningElement { // This is Private property. strName = '' ; } |
In above example, we have declared strName as Private Property. We can access any property in component as {strName}.
My name is {strName} |
Previously, Private properties were not Reactive by nature. In Spring’20 release, all Primitive Private properties are made Reactive. but what is Reactive properties?
Reactive Properties
When value of the property is updated in JS Controller, it should be reflected on UI as well. Only values of the Reactive properties are reflected on UI once it is updated in JS Controller. Primitive Private properties are Reactive by nature but in order to make Non-primitive properties Reactive, we have to use track decorator. So it creates a one way binding from JS Controller to Component.
First import the track decorator in our JS Controller and use @track while declaring property to make it Reactive just like below:
import { LightningElement, track } from 'lwc' ; export default class LwcComp extends LightningElement { // Non-primitive property. @track list = [ ' aura ' , 'lwc ' ]; } |
So whenever list property is updated in JS Controller, it will be reflected on UI
Public Boolean Properties:-
Boolean Public properties works as normal HTML 5 Boolean attributes. When passing value to Boolean property of Child component, we just need to mention the name of Boolean property in Child component tag as attribute like below
< c-child-cmp str-public-name = 'hello' bool-show-name></ c-child-cmp > |
Here, bool-show-name is Public Boolean property. There is no need to assign a value to it. If Boolean property is mentioned, its value will be True even though we assign its value as False explicitly. Hence if you want to pass True, just mention the property name as attribute name in Kebab case. If you want to pass False, don’t mention the property name at all. Hence it is also important to assign default value as False in JS Controller like below:
api boolShowName = false ; |
Getter:-
A Getter is used to compute the static values. Getter is defined in JS Controller just like methods but prefixed with get keyword like below:
get accountName(){ return 'My name is ' + this .strPublicName; } |
To access this Getter on UI, we just need to use {accountName}..
NOTE after spring 20 release the @track decorater has been deprecated .
Comments
Post a Comment