Decorators in Lightning Web Component(LWC)

11 minute read
0
Sfdcpandaschool
What Are Decorators In Lightning Web Component?

A Decorator is a design pattern that allows adding behaviors to Javascript Objects. Decorators which are part of ECMAScript are used to dynamically alter or modify the functionality.

Type of Decorators in Lightning Web Component

There are three type of Decorators in Lightning web components.

  1. Api
  2. Track
  3. Wire

1. @api

To expose a public property or a public method, decorate with @api. Public properties are reactive, also known as public reactive properties since if a value of property changes then component is re-rendered

  • Public properties define API of a component whereas public methods are part of a component’s API
  • A Component is re-rendered when the value of a referenced public property is modified or changed
  • To pass data from parent component to child component, @api decorator in the child component exposes a property by making it public so that parent component can update it
  • @api properties can be exposed in an App builder

Please find the below code snippet that provides an insight how an @api property on child component is set from a parent component:

apiDecoratorSampleChildComponent.html

<template>
    <lightning-card title="Child Component">
        <div class="slds-p-around_medium">
            <p class="slds-p-horizontal_small">{message}</p>
        </div>
    </lightning-card>
</template>

apiDecoratorSampleChildComponent.js

import { LightningElement, api } from 'lwc';
 
export default class ApiDecoratorSampleChildComponent extends LightningElement {
    @api message;
}

apiDecoratorSampleChildComponent.js-meta.xml

apiDecoratorSampleParentComponent.html

<template>
    <c-api-decorator-sample-child-component message = 'Message From Parent Component!!'></c-api-decorator-sample-child-component>
</template>

apiDecoratorSampleParentComponent.js

import { LightningElement } from 'lwc';
 export default class ApiDecoratorSampleParentComponent extends LightningElement {}

2. @track

To expose a private property or a private method, declare with @track. Also known as Private reactive properties

  • To track a private property and to re-render component when that property changes, use @track decorator (Available only for the component where it is declared)
  • Fields which are using @track decorator that contains an object or an array, tells the framework to observe changes to the properties of an object or elements of an array
  • After Salesforce Spring ’20, all the fields in a Lightning Web Component are reactive. If a field is used in a template & value changes, the component re-renders and displays a new value by default

helloWorld.html

<template>
    <lightning-card title="Hello World" icon-name="custom:custom14">
      <div class="slds-m-around_medium">
        <p>Hello, {greetingMessage}!</p>
        <lightning-input label="Name" value={greeting} onchange={changeHandler}></lightning-input>
      </div>
    </lightning-card>
  </template>

helloWorld.js

import { LightningElement } from 'lwc';
export default class HelloWorld extends LightningElement {
  //@track greetingMessage = 'World';//Before Spring ’20 to need to import track decorator & use it to make a field reactive
  greetingMessage = 'World';
 
  changeHandler(event) {
    this.greetingMessage = event.target.value;
  }
}

3. @wire

  • Reactive wire service is utilized in Lightning Web Components to read the Salesforce data from apex class into Lightning web components
  • Component is re-rendered when wire service provisions the data from apex class. The output from apex method is set to a property

Syntax:

import <methodName> from ‘@salesforce/apex/<Namespace.ApexClassName.apexMethod>’;

@wire(methodName, {methodParams})

propertyOrFunction;

methodName: A variable that identifies the Apex method. 

apexMethod: The name of the Apex method to import. 

ApexClassName: The name of the Apex class. 

Namespace: Defines the namespace of the Salesforce organization. Only specify a namespace when the organization doesn’t use the default namespace (c)

displayContacts.html

<template>
    <lightning-card title="Contacts" icon-name="standard:contact_list">
        <div class="slds-m-around_medium">
            <template if:true={contacts.data}>
                <template for:each={contacts.data} for:item="con">
                    <p key={con.Id}>{con.Name}</p>
                </template>
            </template>
        </div>
    </lightning-card>
 </template>

displayContacts.js

import { LightningElement, wire } from 'lwc';
import getContactsList from '@salesforce/apex/ContactsService.getContacts';
 
export default class DisplayContacts extends LightningElement {
 
    @wire(getContactsList) //Wiring the Output of Apex method to a property
    contacts;
}

Decorators is a feature in modern JavaScript that allows annotating and modifying or adding some additional functionalities to classes and class members, like - properties and methods. Using decorators in LWC, we can define and modify the behaviour of components.

There are some built-in decorators provided by LWC that we can use to define properties and methods in components:

  • @api: This annotation is used to define a public property that can be accessed by other components.
  • @wire: This annotation is used to connect a component to an Apex method or a wire adapter.
  • @track: This annotation defines a reactive property that causes the component to re-render when the property changes.
  • @trackMap: This annotation defines a reactive map that causes the component to re-render when the map is modified.
  • @trackArray: This annotation defines a reactive array that causes the component to re-render when the array is modified.
  • @apiMethod: This annotation defines a public method that can be called by other components.
  • @wireMethod: This annotation is defined to connect a component to an Apex method or a wire adapter and returns the result as a reactive property.

In LWC, both @api and @track decorators are used to define properties in a component, but they serve different purposes. The @api decorator is used to define a public property that can be accessed by other components. This allows passing data between components in a parent-child relationship, or between unrelated components using the Lightning Message Service.

Here's an example of how we can use the @api decorator to define a public property:

import { LightningElement, api } from 'lwc';
export default class MyComponent extends LightningElement {
@api message = 'Hello World';
}
Now the component is defined. Other components can access this property using dot notation, like this:
<c-my-component message="Hello from parent"></c-my-component>  
  • The @track decorator is used to define a reactive property, It means suppose there are any changes in the property, then the whole component will be re-rendered. This is useful when we need to update the component's UI based on changes to the property.

Here's an example of how we can use the @track decorator to define a reactive property:

        
import { LightningElement, track } from 'lwc';
export default class MyComponent extends LightningElement {
    @track count = 0;
    handleClick() {
        this.count++;
    }
}

In this example, the count property is defined as a reactive property using the @track decorator. When the handleClick method is called, the count property is incremented and the component re-renders to display the new value.

Post a Comment

0Comments
Post a Comment (0)