إجمالي مرات مشاهدة الصفحة

Decorators in LWC

Decorators in LWC

Decorators are used to add the Additional functionalities to the JavaScript Properties(variables) and functions.
It defines the Level of Access of the Property / Function. i.e. To indicate the the property / function can be accessible within the component / outside of the component.

Lightning Web Components provides the below 3 types of Decorators.
  • @track
  • @api
  • @wire
We can apply the Decorators and JavaScript Properties and Functions as below.

Syntax: (Property):
@DecoratorName <propertyName> = <value>;
Ex:
@track customerCode = 'CID7008945';
@api customerName = 'Ramesh Kumar';
@wire accountRecords;

Syntax: (Functions)
@DecoratorName <FunctionName>()
{
// Write the Business Logic..
}

Ex:
@track handleOnChange()
{
// Write the Business Logic..
}
@api handleOnClick(event)
{
// Write the Business Logic..
}
@track Decorator:

  • Track Decorator is used to make the Properties and Functions are "Private". 
  • Track Decorated properties and functions can be accessible within the component only.
  • We can't access, and we can't assign the values to the Track Decorated properties from outside of the component.
  • Track Decorated properties are "ReActive Properties by default".
  • While defining the Track Decorated properties, we have to import the "Track" namespace inside the component. 
Syntax:

Example:

Define a LWC to represent the Track ReActive property value on the component.

HTML Code




JavaScript Code



@api Decorator
  • @api decorator will make the properties and functions as "Public". i.e. We can access these properties from other Components. And we can invoke these methods from Other Components.
  • @api properties are "ReActive Properties" by default.
Syntax:

@api <propertyName> = <Value>;
Ex:
@api productName = 'Air Conditioner';
@api manufacturer = 'Samsung Inc.';

Syntax:

@api <functionName>()
{
// Write teh Business Logic..
}