Decorators in Lightning Web Component
The Lightning Web Component has three decorators.
@api: If we want to pass any variable from Parent component to child component then we use @api decorator. To pass data to the child component, we need to define a variable with @api decorator in the child component to be public and accessed from the parent component. @api uses for public properties in LWC.
@api decorator Example -
- Import @api decorator in Js file of Lwc.
import { LightningElement, api } from 'lwc';
Without importing @api decorator we can not use @api decorator inLWC. - Create any variable with @api decorator in LWC.
<!- childItem.JS ->import { LightningElement, api } from 'lwc';
export default class childItem extends LightningElement {
@api itemName = 'New Item';
} - Use variables in the html file of LWC.
- @track: If we want to change any value of a field on click of button then in this case we will have to create a variable with @track decorator. @track decorator uses for private properties only. We cannot access variable with @track decorator in another Lightning web component.
@track example -
helloWorld.html - helloWorld.js
import { LightningElement } from 'lwc';
export default class HelloWorld extends LightningElement {
greeting = 'World';
changeHandler(event) {
this.greeting = event.target.value;
}
}
helloWorld.js-meta.xml
@wire: @wire decorator uses for reading the salesforce data. Suppose we want to show the list of all accounts in our lightning web component then for accessing all salesforce data in our lightning web component we will use @wire decorator.
We need to import the @salesforce/apex scoped module into the JavaScript controller class.import apexMethodName from '@salesforce/apex/Namespace.Classname.apexMethodReference';
Here is a list of the important points of importing the apex method:
apexMethodName: An imported symbol that identifies the Apex method.
apexMethodReference: The name of the Apex method to import.
Classname: The name of the Apex class.
Namespace: The namespace of the Salesforce organization. Specify a namespace unless the organization uses the default namespace ©, in which case don’t specify it.
Example of @wire -
Apex class AccountHelperpublic with sharing class AccountHelper {
@AuraEnabled(cacheable=true)
public static List<Account> getAccountList() {
return [SELECT Id, Name, Type, Rating, Phone
FROM Account];
}
}
accountListLWC.js -import { LightningElement, wire } from 'lwc';
import getAccountList from '@salesforce/apex/AccountHelper.getAccountList';
export default class AccountListLWC extends LightningElement {
@wire(getAccountList) accounts;
}
Webner Solutions is a Software Development company focused on developing Insurance Agency Management Systems, Learning Management Systems and Salesforce apps. Contact us at dev@webners.com for your Insurance, eLearning and Salesforce applications.
Originally published at https://blog.webnersolutions.com on January 11, 2022.