Answer – LWC is built using these main parts, including HTML, JS, CSS, and XML.
Answer – The following is the explanation of each part’s usage : HTML – It defines the markup of the LWC. JS – It establishes the component logic and behaviours of LWC. CSS – It defines the styling of LWC. XML – It includes the component’s metadata. Here we defined the attributes such as targets, like where our component will be displayed in the application.
Answer – The following are the rules that we should follow while naming our LWC: The component must start with the lowercase i.e. it should follow camel case. It must contain only alphanumeric or underscore characters, not a dash. While referencing components in HTML we should use the kebab case. Must contain only alphanumeric or underscore characters Below are the samples of the camel case and kebab case
Answer – In LWC we have three types of decorators – api, track and wire
Answer – First of all to use any decorator we should use @ as a prefix then decorator and then variable or property name. 1. @api – It is used to make any property or variable public so that it will be visible to other components for communication. 2. @track – It is used to declare any property or method as private. In LWC all fields are reactive but if the field type is array or object, there are some limits to the depth of changes to be tracked. If we declare them with @track, we can observe the changes. 3. @wire – It is used to interact with salesforce data.
Answer – We have three types of communication in LWC which are Parent to Child Child to Parent Communication between independent component
Answer – Here we have to establish the Parent-Child Communication. It will be done through @api decorator. Let’s look at the below example. We have created two components here childComp and parentComp. We have messageFromParent in childComp which is receiving the value from Parent.
import { LightningElement,api } from 'lwc';
export default class ChildComp extends LightningElement {
@api messageFromParent
}
<template>
<lightning-card variant="Narrow" title="Child Component">
<div>{messageFromParent}</div> </lightning-card>
</template>
<?xml version="1.0"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>57.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__AppPage</target>
</targets>
</LightningComponentBundle>
import { LightningElement } from 'lwc';
export default class ParentComp extends LightningElement {
message = ''
handleChange(event) {
this.message = event.detail.value
}
}
<template>
<lightning-card variant="Narrow" title="Parent Component">
<lightning-input
type="text" variant="standard" name="Message" label="Message" placeholder="type here..." value = {message} onchange={handleChange}></lightning-input> </lightning-card>
<c-child-comp message-from-parent = {message}></c-child-comp>
</template>
<?xml version="1.0"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>57.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__AppPage</target>
</targets>
</LightningComponentBundle>
Answer – Here we have to show Child to Parent Communication. It will be done through the dispatching of the custom event from the child and then the parent component will receive it. Here we have two components childComp and parentComp. In the Child component, we have an input box to enter our value and then on clicking of Send Message button, we will dispatch our event. In Parent component markup, where we defined our child, to catch the event we have to use “on” as a prefix just like we do in the standard events like onclick, and onchange. After that, to handle the event we have a handler in the JS handleMessageFromChild which is receiving the event and in the detail, we have our value. Below is a sample of Child to Child-to–Parent communication.
import { LightningElement, api } from 'lwc';
export default class ChildComp extends LightningElement {
messageFromChild = ''
handleChange(event) {
this.messageFromChild = event.detail.value
}
handleClick() {
const eve = this.dispatchEvent(new CustomEvent('send', { detail: this.messageFromChild }))
}
}
<template>
<lightning-card variant="Narrow" title="Child Component">
<lightning-input type="text" variant="standard" name="Message" label="Message" placeholder="type here..."
value={messageFromChild} onchange={handleChange}></lightning-input>
<lightning-button label="Send Message" title="Send Message" onclick={handleClick}></lightning-button>
</lightning-card>
</template>
<?xml version="1.0"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>57.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__AppPage</target>
</targets>
</LightningComponentBundle>
import { LightningElement } from 'lwc';
export default class ParentComp extends LightningElement {
messageRecieved = 'No Message'
handleMessageFromChild(event) {
this.messageRecieved = event.detail
}
}
<template>
<lightning-card variant="Narrow" title="Parent Component">
<div>Message from child is : {messageRecieved} </div> </lightning-card>
<c-child-comp message-from-child={messageRecieved} onsend = {handleMessageFromChild}></c-child-comp>
</template>
<?xml version="1.0"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>57.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__AppPage</target>
</targets>
</LightningComponentBundle> Initially, we are displaying No Message then receiving the value from the child.
Answer – The promise function basically helps us to run a code asynchronously and it returns success and failure event upon completion. It has different states: Pending: The initial state Fulfilled: The operation was completed successfully ie resolved. Rejected: The operation failed.
Answer – There are two ways to call the apex method in LWC – Using wire services Using Imperative method Call Apex using @wire Decorator: You can @wire a property or a function to receive the data from Apex. You have to annotate your apex method with @AuraEnabled(cacheable=true). By using the wire services it reduces the server call because it loads the data from the cache. We can’t do DML with a wire decorator. Imperative Call If we want to invoke our method call on some click or to control our method invocation we have to call the method imperatively. Calling our method in this way is also helpful if we want to perform some DML operations. Here, we don’t annotate our method (cacheable=true). Sample Code for wire and imperative Here we have the getAccount method that we imported from our Apex controller and returned account data where ID matches to accId. While using wire, to make the variable reactive and receive ID from the record page, we can annotate it with @api and display it with a $ sign. However, in the imperative call, it is different, we use it with this.accId and in imperative it will return the promise. Where .then is the resolve and .catch is the reject,
// wire call
@wire(getAccount,{ accId: '$accId' })
wiredAccResult({ data, error }) {
if (data) { console.log('data coming for accounts are ', data) console.log('length of data coming for accounts are ', data.length)
}
if (error) { console.log('Error in fetching account ', JSON.stringify(error.message));
}
}
// Imperative call
fetchAccount(){
getAccount({ accId: this.accId})
.then(data=>{
//console.log('length of data coming for accounts are ',data.length)
})
.catch(error=>{
console.log('Error occurred while fetching account ',error.body.message)
})
}
Answer – The lifecycle hooks in LWC provide an ability to control your code at various stages. We have different types of lifecycle hooks in LWC which run in a specific order: 1. constructor() 2. ConnectedCallback() 3. RenderedCallback() 4. DisconnectedCallback() 5. ErrorCallback() Note: If we also have the child component, Child flow will run after the connectedCallback and before the renderedCallback in the same order.
Answer – Conditional rendering in Salesforce helps to show content based on specific conditions. We can achieve this by template if:true or with new lwc:if, lwc:elseif, and lwc:else.
Answer – For:each and Map both are used to handle Arrays. But the major difference between them is that we can update the element in for:each while iterating but it doesn’t return the new array. However, Map returns the new array with the modified elements.
Answer – It is not possible to call Aura inside LWC but vice versa is likely that we can call LWC inside Aura.
Answer – Suppose we have 3 components childComp, parentComp, and grandParentComp and we want to communicate from child to grandparent then while dispatching the event we can set the bubble and composed property as true so that the event can move up to a higher hierarchy And can easily cross the Shadow boundary. As we see in the event bubbling event is moving from bottom to top. The same in event capturing event is moving from top to bottom.
Answer – It shows communication between unrelated components so here we will establish communication via Lightning Message Service. In this case, we will have to create a message channel, a publisher component from which we have to send the data and a subscriber component from which we have to receive the data.
Answer – Here we can have the following issues: We can check if <isExposed>true</isExposed> is true or not because if it is false, the component itself is not visible. We can also check if a component is visible to the correct target, if we want to deploy that component in the Lightning App Page then the target should be like this <target>lightning__AppPage</target>. Similarly, we have to check for correct targets. If both the above points work fine, then we have to check the Apex class sharing. If the class is using sharing and that user does not have access to those contact records then it might be the issue. Also, we can check whether SOQL is working fine or not. We can check if SOQL is returning to user mode or system mode and if in the user mode then the user should have the correct access. We can also check if the user can access the apex class in the Profile or Permission Set.
Answer – This scenario can be achieved by using a standard base component viz lightning-record-form. They are useful when we have a simple requirement like that. Below is the code to achieve this.
import { LightningElement } from 'lwc';
import CONTACT_LastName_FIELD from '@salesforce/schema/Contact.LastName';
import CONTACT_FirstName_FIELD from '@salesforce/schema/Contact.FirstName';
import CONTACT_Email_FIELD from '@salesforce/schema/Contact.Email';
import CONTACT_OBJECT from '@salesforce/schema/Contact';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
export default class ContactCreator extends LightningElement {
objectApiName = CONTACT_OBJECT
fields = [CONTACT_Email_FIELD, CONTACT_FirstName_FIELD, CONTACT_LastName_FIELD];
handleSuccess(event) {
const toastEvent = new ShowToastEvent({
title: "Contact created",
message: "Record ID: " + event.detail.id,
variant: "success"
});
this.dispatchEvent(toastEvent);
}}
<template>
<lightning-card>
<lightning-record-form object-api-name={objectApiName} fields={fields}
onsuccess={handleSuccess}></lightning-record-form> </lightning-card>
</template>
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" fqn="helloWorld">
<apiVersion>52.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__AppPage</target>
<target>lightning__HomePage</target>
</targets>
</LightningComponentBundle> Here Cancel and Save buttons will come automatically with the record form and clicking on Save button it fire the onsuccess event. If we want to perform some additional things we can handle that.
Answer – To achieve this scenario we have to utilize the meta xml file. There we have to define our target config and the property name, with its type, default value and label. Below is the sample code and output. We have created a helloWorld lwc component to demonstrate this. When we deploy this component we will have the option to provide the custom message.
<template>
<lightning-card title="HelloWorld" icon-name="custom:custom14">
<div class="slds-m-around_medium"> <p>Hello, {greeting}!</p> </div> </lightning-card>
</template>
import { LightningElement, api } from 'lwc';
export default class HelloWorld extends LightningElement {
@api greeting;
}
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" fqn="helloWorld">
<apiVersion>52.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__AppPage</target>
<target>lightning__RecordPage</target>
<target>lightning__HomePage</target>
</targets>
<targetConfigs>
<targetConfig targets="lightning__HomePage,lightning__AppPage,lightning__RecordPage">
<property name="greeting" type="String" default="Welcome in Salesforce"
label="Enter the message" />
</targetConfig>
</targetConfigs>
</LightningComponentBundle>
Answer – Here in the child component we have to annotate our method as @api. so suppose I have method in child component handleData So below will be the syntax for child component
@api
handleData(){
// any logic
}
parent component
handleChange(){
this.template.querySelector('c-child-comp').handleData();
Answer – Lightning Message Service is used to communicate across different components like between unrelated components, Aura, and VisualForce.
Answer – Lightning Data Service is helpful to connect our component with data without actually calling, apex. We can use LDS to create, update, and delete our records when we have simple requirements which don’t require any complex logic to perform.
Answer – It is a way to write an asynchronous code. Async is a keyword used to define an asynchronous function which returns a promise and await is used to pause that execution until the async returns the promise whether resolved or rejected.
Answer – uiRecordApi is the module in LWC that provides us with various methods to create, update, and delete records. Following are the Javascript methods included in the uiRecordApi module: createRecord(recordInput) createRecordInputFilteredByEditedFields(recordInput, originalRecord) deleteRecord(recordId) generateRecordInputForCreate(record, objectInfo) generateRecordInputForUpdate(record, objectInfo) getFieldValue(record, field) getFieldDisplayValue(record, field)
Answer – No It is not possible to perform DML inside wire as it fetches data from cache.
Answer – When we used the constructor lifecycle hook it was mandatory to use a super() keyword to call the properties of its parent component. It is used to call its parent class in the hierarchy.
Answer – Component events – A component event can be handled by the component that fired the event or by a component in the containment hierarchy that receives the event. They are the events used to communicate across parent and child components. Application events – They are global events which used to communicate across multiple components. They follow the pub-sub model when an event is fired then all the components handling that event will be notified.
Answer – Promise.all take multiple promises and return the promises when all gets fulfilled and will reject immediately upon any of the input promises rejecting. Promise.race also takes multiple promises but it returns a single promise whichever settles first or we can say whichever resolves first unlike promise.all.
Answer – Shallow copy creates the copy of an object but not for its nested properties. It creates a reference to it. So any changes to the nested properties of a copied object will also change to the original one. Like spread operator creates the shallow copy. But for a deep copy, it is different, it creates the copy without actually referencing them so any changes in the copied object will not affect the original one and by JSON.stringify(JSON.parse(obj1)) we can create the deep copy of objects.
Answer – Reduce function iterates on the array’s every element and accumulates them into a single value. Below is an example. Here index is basically we can say the collector, currentItem is the current value of the array that is being iterated and 0 is the starting point. So when it starts to iterate It goes like 0+1 (0 goes into the index as first time and currentItem is the 1) –> 1+2 ( now the index value will be 1 and currentItem is 2) it goes on like that.