Decorators are literally used to decorate the code with clean syntax. They are simple functions and placed immediately before the code that is being decorated.
import {LightningElement, decoratorName} from 'lwc';
In Lightning Web Components, we are having three types of Decorators.
Here, we have shown in detail how to decorate a method or a property-
@decoratorName
getMethodName()
{
return somevalue;
}
Ex: @track
getName()
{
return name;
}
@decoratorName propertyName='propertyValue';
Ex: @api name = ‘John’;
Import the @api decorator from lwc as shown below:
import { LightningElement, api } from 'lwc';
export default class TodoItem extends LightningElement {
@api name= 'John';
}
Let us understand @api decorator with the help of an example:
We have 2 components:
In .html-
In .js-
Here, we have a course as public property as it is decorated with the @api course. Now, parent components can make use of this Public Property course.
In .html-
Here, Course is the public property (i.e @api) of the child component so its values can only be passed by parent components as shown above.
In .js-
Final Output:
import { LightningElement, track } from 'lwc';
Example:
We have a component named as track_example–
In .html-
In .js-
Here,
Then, Click on ‘Update Message’ Button.
import { LightningElement, wire} from 'lwc';
public class wireFromLWC {
@auraEnabled(cacheable = true)
public static string retrunName(){
return ‘John’;
}
}
In this blog, we have learned about the decorators used in the Lightning Web Components (LWC) that can add the functionality to a method or a property as per the business requirements.
All the above-mentioned decorators are unique to LWC. I hope that you find this information beneficial for your next project.
Thank You for reading!