Decorators in LWC

Decorators in LWC and its Types | Salesforce Lightning Tutorial

In this Blog, we are going to understand the topic of decorators in LWC. It is a part of EcmaScript which is used to add extra functionality to your function or methods. The Lightning Web Component programming model has three decorators that add functionality to a property or a function. 

Types of Decorators: 

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

@api decorator

To expose the public property, decorate a field with @api. Public properties define the API for a component. 

Public properties used in a template are reactive. If the value of a public property used in a template changes, the component re-renders. 

An Owner component that uses a component in its markup can access the component’s public properties via DOM properties. 

dont miss out iconDon't forget to check out: Deploying LWC OSS Apps to Heroku With and Without Express API Server | Salesforce Developer Guide

Import @api decorator

Import { LightningElement , api } from ‘lwc’; 
Example :- 
// childComp.js  
import { LightningElement, api } from  'lwc';  
export  default  class  ChildComp  extends  LightningElement { 
    @api headerLabel = 'This Label is from ChildComp.js';
}

@track decorator

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. 

When a field is decorated with @track, Lightning Web Components tracks changes to the internal values of: 

  1. Plain objects created with{} 
  2. Arrays created with [] 

Import @track decorator

import { LightningElement, track} from 'lwc'; 
Example: -  
// childComp.js 
import { LightningElement, track} from  'lwc';  
export default class ChildComp extends LightningElement {  
    @track greeting = 'Hello World';  
    changeHandler(event) { 
        this.greeting = event.target.value;
    }
}

dont miss out iconCheck out another amazing blog by Bhawana here: Javascript for Lightning Web Component | Salesforce Lightning

@wire decorator 

To read Salesforce data, Lightning Web Components use a reactive wire service. When the wire service provisions data, the component re-renders. 

Components use @wire in their JavaScript class to specify a wire adapter or an apex method. 

Import @track decorator

import { LightningElement, wire } from  'lwc';

 

Responses

Popular Salesforce Blogs