Decorators in Salesforce Lightning Web Component(LWC) : Bijay Kumar

Decorators in Salesforce Lightning Web Component(LWC)
by: Bijay Kumar
blow post content copied from  SalesForce FAQs
click here to view original post



### Summary of Decorators in Salesforce Lightning Web Components (LWC) In this tutorial, we explore decorators in Salesforce Lightning Web Components (LWC), which are special JavaScript annotations that modify the behavior of properties and methods in LWC. They help establish a connection between the component and the Salesforce org, allowing for dynamic data fetching based on the `recordId`. #### Key Points: 1. **What are Decorators?** - Decorators are JavaScript annotations that provide metadata to the LWC framework, influencing how properties and methods are handled. 2. **Types of Decorators:** - **@api**: Exposes public properties and methods, allowing parent components to pass data to child components. - **@track**: Used to make properties reactive. However, since Spring '20, all properties are reactive by default, making this decorator less necessary for simple properties. - **@wire**: Fetches data from Apex classes into LWC, allowing for dynamic data binding. 3. **Using @api Decorator:** - To make a property public, you declare it with `@api`. This allows the component to receive data from parent components. For example, a `recordId` can be fetched dynamically. 4. **Using @track Decorator:** - Previously used to make properties reactive, but now properties are reactive by default. It is still useful for complex objects or arrays. 5. **Using @wire Decorator:** - This decorator is used to call Apex methods and retrieve data. It handles data retrieval and error management seamlessly. #### Example Scenarios: - **@api**: A component displays account details based on the `recordId` passed from a parent component. - **@track**: A greeting message updates reactively based on user input. - **@wire**: An account list is fetched from an Apex class and displayed in a data table. ### Conclusion Understanding decorators in LWC is crucial for effective Salesforce development. They enable dynamic data handling and improve component interaction. ### Additional Information For further reading, consider exploring topics like: - Adding toggle buttons to LWC data tables. - Implementing search functionality in LWC data tables. - Displaying images in LWC data tables. ### Hashtags for SEO #Salesforce #LightningWebComponents #LWC #SalesforceDevelopment #WebDevelopment #JavaScript #Apex #SalesforceTutorial #API #Track #Wire #DynamicData #ComponentDevelopment


As a Salesforce developer, whenever we want to create a lightning web component that displays details from sObjects. To receive the recordId and fetch the data dynamically from the Salesforce org to the component, we use decorators to establish a connection between LWC and the Salesforce org.

In this tutorial, we will learn about decorators in Salesforce Lightning Web Component. I will explain what decorators are in LWC, their types, their uses, and how to use them in Salesforce LWC with real-time scenarios and explanations.

What are the Decorators in Salesforce Lightning Web Component?

The decorators in LWC are JavaScript annotations that modify the behaviour of properties and methods. They act as special markers that provide additional information (metadata) to the LWC framework about how to handle certain variables or methods in a component.

For example, you are creating a component that displays Account details. The decorator allows the component to receive the recordId from a parent component or record page and fetches the account data dynamically from Salesforce when the recordId changes.

Different Types of Decorators in LWC

There are three types of decorators in lightning web components.

  1. @Api:
  2. @Track:
  3. @Wire:

Now let’s understand the uses of the above decorators and how to use them in the lightning web component.

@api Decorator in Salesforce Lightning Web Component

The @api decorator is used to expose a public property or a public method that is declared in the JS file. Public properties are reactive, also known as public reactive properties, since if the value of a property changes, then the component value also gets changed.

  • Public properties define the API of a component, whereas public methods are part of a component’s API.
  • To pass data from parent component to child component, the @api decorator in the child component exposes a property by making it public so that the parent component can update it.
  • @api properties can be exposed in an App builder.

Use @api Decorator in Salesforce Lightning Web Component

In the LWC, I will explain how we can use the @api decorator in Salesforce lightning web component to make a variable or property public.

First, we will take an example to understand the @api decorator in Salesforce LWC. In that, I will explain what will happen if we do not declare @api in the LWC component, and then we will see after declaring @api decpoartor what changes will happen after declaring the @api decorator.

Create LWC JS File: (Without Using @api Decorator)

First, we created a JS file in which we declared variables to store the message and the record ID. However, we didn’t declare the @api decorator in this JS file.

import { LightningElement } from 'lwc';

export default class ApiDecorator extends LightningElement {

    message = 'Private Property';
    recordId;
}

2. HTML File:

Then in the HTML file, we added the lightning card to display the information with title and icon. After that, we provided labels and passed JS variables to the labels to display information of the declared variables.

Then we added a condition to display the message if the record ID fetched, that means true={recordId}. Then display the fetched record ID. Otherwise, display the message ‘No Record ID Found’.

<template>
    <lightning-card title="Account Info" icon-name="standard:account">

        <p class="slds-p-around_medium">Message: {message}</p>
        <p class="slds-p-around_medium">Record ID: {recordId}</p>

        <template if:true={recordId}>
            <p class="slds-p-around_medium">Fetched Record ID: {recordId}</p>
        </template>

        <template if:false={recordId}>
            <p class="slds-p-around_medium">No Record ID Found</p>
        </template>

    </lightning-card>
</template>

3. XML File:

In the XML file, we need to declare where we want to place the created component. We can add the component to the following places in the Salesforce org.

  1. lightning__AppPage: This allows you to add a component to the App Page in Salesforce org (e.g., Sales App).
  2. lightning__RecordPage: This allows you to add a component to the Record Page in Salesforce org (e.g., Any Account Record).
  3. lightning__HomePage: This allows you to add a component to the Home Page in Salesforce org.

By default, the <isExposed>tag is false. You need to make it true, and then you can specify the place where you want to add the component. After that, deploy the LWC component to the org.

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>62.0</apiVersion>

    <isExposed>true</isExposed>
    <targets>
        <target>lightning__RecordPage</target>
    </targets>

</LightningComponentBundle>

Deployed Component (Without Using @api Decorator)

In the below image, you can see we have added the LWC component to the account record page, displaying only the message variable value that we provided in the JS file. However, it should also display the currently opened account record ID in the Record ID field.

Instead of displaying the ‘No Record ID Found’ message. This happened because we didn’t declare the @api decorator in the JS file while declaring the recordId variable.

Decorators in Salesforce Lightning Web Component

Create LWC JS File: (Using @api Decorator)

Now, let’s declare the @api decorator in the JS file before the variable name in the import statement. This will allow us to expose a public property(variable) or a public method declared in the JS file so that the record ID can be displayed in the deployed component Salesforce org.

Then don’t change the HTML and XML file. Save the JS file and deploy the LWC component to the Salesforce org again.

import { LightningElement, api } from 'lwc';

export default class ApiDecorator extends LightningElement {

    message = 'Private Property';
    @api recordId;
}

Deployed Component (Using @api Decorator):

Now you can see the deployed component, now it shows the ID of the currently opened account record.

Salesforce api Decorators in LWC

In this way, we can use the @api decorator in Salesforce LWC to make variables and methods public, which are declared in the JS file.

@track Decorator in Salesforce Lightning Web Component

The @track decorator in Salesforce LWC was used in earlier versions of LWC to make properties reactive, but it is now for simple properties like @track myVar(variable name).

Since Spring ’20, all properties in a component are reactive by default. If LWC contains objects or arrays, we need to use the @track decorator.

Use @track Decorator in Salesforce Lightning Web Component

Here, I will explain why and how we used to declare the @track decorator before the Spring ’20 release, and in the same LWC component, I will explain the changes made after the release in the @track decorator.

1. Create LWC JS File:

In the JS file, first, we declared greetingMessage with the @track decorator, which is used to make properties reactive, meaning they automatically trigger re-rendering when their value changes.

But after the Spring 20 release, we don’t need to declare the @track decorator to achieve that functionality. So, while declaring a variable, I didn’t use a decorator, and will see even though the functionality of the @track decorator will work.

We declared the event so that when it occurs, the declared variable value will be rendered in the HTML field.

import { LightningElement } from 'lwc';

export default class TrackAPI extends LightningElement {

    // @track greetingMessage = 'World';
    greetingMessage = 'World';
 
    changeHandler(event) {
    this.greetingMessage = event.target.value;
    }
}

2. Create LWC HTML File:

In the HTML file, we displayed the value from the JS variable and then called the event that will happen on change.

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

3. XML File:

In XML we ned to declare on which page we want to place the created component. After that, save the files and deploy to the Salesforce org.

<isExposed>true</isExposed>
    <targets>
    <target>lightning__RecordPage</target>
    </targets>

4. Deployed Component (Without Using @track Decorator)

Now, here you can see we don’t even use the @track decorator, and even when we provide the value in the name field, it renders after the hello word.

track Decorator in LWC

@wire Decorator in Salesforce Lightning Web Component

The @wire decorator in Salesforce LWC is used to fetch or to read the Salesforce data from the apex class into Lightning web components. That means it is a way to get and bind data from apex.

There are two ways to declare the @wire decorator in LWC.

  1. Weird service for predefined module.
  2. To use wire in the Apex class method.

Use @wire Decorator in Salesforce Lightning Web Component

In the example below, I explained how to use @wire to fetch account records and display them in an LWC component.

1. Create Apex Class:

In the Apex class below, the @AuraEnabled(cacheable=true) annotation makes the method accessible in LWC and improves performance by enabling caching. Then we created a list collection with the method which returns a list of account records with selected fields.

public with sharing class accountController {
    @AuraEnabled(cacheable=true)
             public static List<Account> getAccounts() {

                    return [SELECT Id, Name, Account_Priority__c, Rating FROM Account WHERE  Account_Priority__c != NULL  LIMIT 10];

      }
}

2. Create LWC JS File:

The AccountList LWC is designed to fetch and display a list of accounts with some fields using the @wire decorator.

In the LWC JavaScript file, we declared the wire decorator in the import statement first to make it usable. Then in another import statement, we provided the method name from the class path and again the method name.

It retrieves the data from an Apex method (getAccounts) that queries account records. The component defines a columns array, specifying the table headers and mapping them to corresponding field names in Salesforce.

The @wire function dynamically handles data retrieval: if successful, the account records are stored in this.accounts, making them available for display; otherwise, any encountered error is stored in this.error for handling.

The component is intended to be used with a lightning-datatable in the HTML file to present the account information in a structured format.

import { LightningElement, wire } from 'lwc';
import getAccounts from '@salesforce/apex/AccountController.getAccounts';

export default class wireDecorator extends LightningElement {
    accounts;
    error;

    columns = [
        { label: 'Account Name', fieldName: 'Name' },
        { label: 'Account Priority', fieldName: 'Account_Priority__c' },
        { label: 'Rating', fieldName: 'Rating' }
    ];

    @wire(getAccounts)
    wiredAccounts({ data, error }) {
        if (data) {
            this.accounts = data;
            this.error = undefined;
        } else if (error) {
            this.error = error;
            this.accounts = undefined;
        }
    }
}

3. Create LWC HTML File:

This HTML template is designed to display a list of accounts in a table format using a lightning-datatable. Then the component checks if the accounts data exists using <template if:true={accounts}>. If data is available, it displays in a lightning-datatable, using.

If an error occurs while fetching the data, the <template if:true={error}> condition displays an error message (slds-text-color_error).

<template>
    <lightning-card title="Account List" icon-name="standard:account">
        <template if:true={accounts}>
            <lightning-datatable
                key-field="Id"
                data={accounts}
                columns={columns}>
            </lightning-datatable>
        </template>
        <template if:true={error}>
            <p class="slds-text-color_error">Error loading accounts!</p>
        </template>
    </lightning-card>
</template>

4. XML File:

In XML we ned to declare on which page we want to place the created component. After that, save the files and deploy to the Salesforce org.

<isExposed>true</isExposed>
    <targets>
    <target>lightning__RecordPage</target>
    </targets>

5. Deployed Component (Using @wire Decorator)

Now, here you can see the fields and records we retrieved in the Apex class, we displayed in the data table using HTML file, and to use the retrieved account data, we used @wire decorator to access data from the Apex class to LWC.

wire Decorators in Salesforce Lightning Web Component

Conclusion

I hope you have got an idea about decorators in Salesforce Lightning Web Component. I have explained what decorators are in LWC, their types, their uses, and how to use them in Salesforce LWC with real-time scenarios and explanations.

You may like to read:

The post Decorators in Salesforce Lightning Web Component(LWC) appeared first on SalesForce FAQs.


March 09, 2025 at 11:48PM
Click here for more details...

=============================
The original post is available in SalesForce FAQs by Bijay Kumar
this post has been published as it is through automation. Automation script brings all the top bloggers post under a single umbrella.
The purpose of this blog, Follow the top Salesforce bloggers and collect all blogs in a single place through automation.
============================

Salesforce