LWC: Using Decorators in Lightning Web Components

 LWC: Using Decorators in Lightning Web Components

Lightning Web Components framework provides us with three decorators that adds functionality to a property or a function. These decorators are unique to Lightning Web Component framework.

There are three types of Decorators

  1. @api
  2. @track
  3. @wire

@api:

If we want to expose a public property then we need to decorate the field with @api. These public properties are reactive and if the value in the public property changes then the component rerenders Automatically. Public methods are part of component’s API. To communicate down the containment Hierarchy, Owner and Parent Components can call JavaScript methods on child Components.

In order to decorate the field, we need to first import @api from lwc.

import { LightningElement, api } from 'lwc';

Note: Property names in JavaScript are in camelCase(first word starts in lowercase and first letter of second word will start with Capital letter) while HTML attribute names are in kebab case(all the words are in lowercase and dash-separated) to match HTML standards.

Example::

// todoItem.js
import { LightningElement, api } from 'lwc';
export default class TodoItem extends LightningElement {
    @api itemName = 'New Item';
}
<!-- todoItem.html -->
<template>
    <div class="view">
        <label>{itemName}</label>
    </div>
</template>
<!-- todoApp.html -->
<template>
    <div class="listing">
        <c-todo-item item-name="Milk"></c-todo-item>
        <c-todo-item item-name="Bread"></c-todo-item>
    </div>
</template>

@track:

Track is used for private properties that want to be rerendered on the component. If a field’s value changes and the field is used in a template or in a getter of a property that’s used in a template, the component rerenders and displays the new value.

Note: After Spring 2020 we need not use @track decorator for private properties as salesforce automatically re-renders the component when there is a change to property.

 

<!-- helloExpressions.html -->

<template>
    <lightning-card title="HelloExpressions" icon-name="custom:custom14">
        <div class="slds-m-around_medium">
            <lightning-input
                name="firstName"
                label="First Name"
                onchange={handleChange}
            ></lightning-input>
            <lightning-input
                name="lastName"
                label="Last Name"
                onchange={handleChange}
            ></lightning-input>
            <p class="slds-m-top_medium">
                Uppercased Full Name: {uppercasedFullName}
            </p>
        </div>
    </lightning-card>
</template>  


Usage of @track before Spring 2020.

// helloExpressions.js

import { LightningElement } from ‘lwc’;

export default class TrackExample extends LightningElement {
@track firstName= ;
@track lastName= ;

handleChange(event) {
const field = event.target.name;
if (field === ‘firstName’) {this.firstName= event.target.value;
} else if (field === ‘lastName’) {this.lastName= event.target.value;
}
}

get uppercasedFullName() {
return `${this.firstName} ${this.lastName}`.trim().toUpperCase();
}
}

@wire:
Lightning web components use a reactive wire Service to read salesforce Data. We can invoke apex method from the component using wire service.

To call an Apex method, a Lightning web component can:

Wire a property
Wire a function
Call a method imperatively

To implement @wire decorator, import @salesforce/apex scoped module into JavaScript  file.

import apexMethodName from '@salesforce/apex/Namespace.Classname.apexMethodReference';
  • 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—If the class is in the same namespace as the component, don’t specify a namespace. If the class is in a managed package, specify the namespace of the managed package.

When an Apex class name changes outside of the JavaScript source file, the class name is automatically updated in the JavaScript source file. Method and argument name changes aren’t updated in the JavaScript source file.

To expose an Apex method to a Lightning web component, the method must be static and either global or public. Annotate the method with @AuraEnabled.

public with sharing class ContactController {
    @AuraEnabled(cacheable=true)
    public static List<Contact> getContactList() {
        return [
            SELECT Id, Name, Title, Phone, Email, Picture__c
            FROM Contact
            WHERE Picture__c != null
            WITH SECURITY_ENFORCED
            LIMIT 10
        ];
    }
}

 

 


Salesforce Documentation

sfdclightning

Related post