Select your Language

Difference between Api, Track and Wire decorator in LWC

 Decorator enhance the functionality of properties and function .

These are often used in Java script.

You can import multiple decorator but a single property of function can have only one decorator.

@api-

  • Marks a property as public.
  • Allowing a parent component to pass data to a child component.
  • This decorator in the child component exposes a property by making it public so that parent component can update it.
Child comp

<template> <lightning-card title="Child Component"> <div> <p>{message}</p> </div> </lightning-card> </template>

Child JS code

import { LightningElement, api } from 'lwc'; export default class ChildComponent extends LightningElement { @api message; }

Parent comp

<template> <c-child-component message = 'Message From Parent Component!!'></c-child-component> </template>

Parent JS code

import { LightningElement } from 'lwc'; export default class ParentComponent extends LightningElement {}


@Track
  • To expose a private property or a private method
  • To track a private property and to re-render component when that property changes, use @track decorator
  • Fields which are using @track decorator that contains an object or an array, tells the framework to observe changes to the properties of an object or elements of an array not the full array.
EX-
<template> <lightning-card title="Hello World" icon-name="custom:custom14"> <div> <p>Hello, {greetingMessage}!</p> <lightning-input label="Name" value={greeting} onchange={changeHandler}></lightning-input> </div> </lightning-card> </template>

import { LightningElement } from 'lwc'; export default class HelloWorld extends LightningElement { //@track greetingMessage = 'World';//Before Spring ’20 to need to import track decorator & use it to make a field reactive greetingMessage = 'World'; changeHandler(event) { this.greetingMessage = event.target.value; } }


@Wire
  •  Wire service is utilized in Lightning Web Components to read the Salesforce data from apex class into Lightning web components
  • Component is re-rendered when wire service provisions the data from apex class. The output from apex method is set to a property
<template> <lightning-card title="Contacts" icon-name="standard:contact_list"> <div> <template if:true={contacts.data}> <template for:each={contacts.data} for:item="con"> <p key={con.Id}>{con.Name}</p> </template> </template> </div> </lightning-card> </template>

JS

import { LightningElement, wire } from 'lwc'; import getContactsList from '@salesforce/apex/ContactsService.getContacts'; export default class DisplayContacts extends LightningElement { @wire(getContactsList) //Wiring the Output of Apex method to a property contacts; }








Reference from- https://www.apexhours.com/decorators-in-lightning-web-component/

No comments:

Post a Comment