Wednesday, March 22, 2023

LWC Conditional Rendering using lwc:if, lwc:elseif, and lwc:else


We used to add the if:true|false directive to a nested <template> element that enclosed the conditional content to render HTML conditionally. Nevertheless, with Spring 23, we may use new lwc:if, lwc:elseif, and lwc:else to do Conditional Rendering in LWC.

In this blog article, we will discuss the lwc:if, lwc:elseif, and lwc:else conditional directives that were added in the Spring'23 release. We will also look at how the lwc:if, lwc:elseif, and lwc:else conditional directives supplant the old if:true and if:else directives.

What Is Conditional Rendering?

Conditional rendering is a method of displaying components or elements based on a given circumstance in the lightning web component (lwc).

This template has a Show Message checkbox. The handleChecboxChange function sets the value of the showMessage property when a user chooses or deselects the checkbox. If the showMessage attribute is set to true, the lwc:if directive shows the nested template Good Morning! Otherwise, it will show select the checkbox to see the message!.

<!-- conditionalRendering.html -->
<template>
<lightning-card title="ConditionalRendering" icon-name="custom:custom14">
<div class="slds-m-around_medium">
<lightning-input type="checkbox" label="Show Message" onchange={handleChecboxChange}></lightning-input>
<template lwc:if={showMessage}>
<div class="slds-m-vertical_medium">
Good Morning!
</div>
</template>
<template lwc:else>
<div class="slds-m-vertical_medium">
<b> select the checkbox to see the message ! </b>
</div>
</template>
</div>
</lightning-card>
</template>


It is important to note that the JavaScript does not affect the DOM; instead, it merely changes the value of a property.

// conditionalRendering.js
import { LightningElement } from 'lwc';

export default class ConditionalRendering extends LightningElement {
showMessage = false;

handleChecboxChange(event) {
this.showMessage=event.target.checked;
}
}























Thursday, March 2, 2023

How to create and run Node.js project in VS code editor ?



   Step 1: Create an empty folder and move it into that folder from your VS Code                           editor, use the following command.

mkdir pro
cd pro
Step 2: Now create a file app.js file in your folder as shown below.

Step 3: Installing Module: Install the modules using the following command.
npm install express
npm install nodemon
Step 4: Add these two commands which are important for running and dynamically running the code after changes made in your Node.js app respectively in package.json file.
{
  "name": "pro",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node app.js",
    "dev": "nodemon app.js"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.17.1",
    "nodemon": "^2.0.12"
  }
}
Step 5: Write down the following code in app.js file.
// Requiring module
const express = require('express');
 
// Creating express object
const app = express();
 
// Handling GET request
app.get('/', (req, res) => {
    res.send('A simple Node App is '
        + 'running on this server')
    res.end()
})
 
// Port Number
const PORT = process.env.PORT ||5000;
 
// Server Setup
app.listen(PORT,console.log(
  `Server started on port ${PORT}`));
Step 6: Run the application using the following command:
npm run dev
Step 7: Now go to http://localhost:5000/  in your browser, you will see the following output: 


Wednesday, January 4, 2023

Date Validation in LWC

 



dateValidation.html

 <template>

<lightning-card title="Date Validation in LWC">
<div class="slds-p-around_medium">
<lightning-input type="date" name="startDate" label="Start Date"
onchange={dateHandler}></lightning-input>
<lightning-input type="date" name="endDate" label="End Date"
onchange={dateHandler}></lightning-input>
<template if:true={error}>
<p class="slds-text-color_error">{error}</p>
</template>
<lightning-button variant="brand" label="submit" onclick={submitHandler}
class="slds-m-top_medium"></lightning-button>
</div>
</lightning-card>

</template>  


dateValidation.js

import { LightningElement } from 'lwc';

export default class DateValidation extends LightningElement {
startDate
endDate
error
dateHandler(event){
const {name, value} = event.target
this[name] = value
}

submitHandler(){
if(this.validateDate(this.startDate, this.endDate)){
console.log("Date is Valid")
} else{
this.error = "Invalid Input...End Date cannot be greater than Start Date"
}
}

validateDate(startDate, endDate){
return new Date(startDate).getTime() < new Date(endDate).getTime()
}
}

Generate CSV in LWC

 


CsvController.cls

public with sharing class CsvController {
@AuraEnabled(cacheable=true)
public static List<Account> getAccounts(){
return [SELECT Id, Name, Phone, AnnualRevenue, Industry from Account];
}
}


csvDemo.html
<template>
<lightning-card title="CSV Demo">
<div class="slds-p-around_medium">
<template if:true={accountData}>
<template for:each={accountData} for:item="account">
<p key={account.Id}>{account.Name}</p>
</template>
</template>
<lightning-button label="Generate CSV" onclick={csvGenerator}
variant="brand"></lightning-button>
</div>
</lightning-card>
</template>

csvDemo.js
import { LightningElement, wire } from 'lwc';
import getAccounts from '@salesforce/apex/CsvController.getAccounts'
import {exportCSVFile} from 'c/utils'
export default class CsvDemo extends LightningElement {
accountData
accountHeaders={
Id:"Record Id",
Name:"Name",
AnnualRevenue:"Annual Revenue",
Industry:"Industry",
Phone:"Phone"
}
@wire(getAccounts)
accountHandler({data, error}){
if(data){
console.log(data)
this.accountData = data
}
if(error){
console.error(error)
}
}

csvGenerator(){
//headers, totalData, fileTitle
exportCSVFile(this.accountHeaders, this.accountData, "account_records")
}
}


utils.js

  export function exportCSVFile(headers, totalData, fileTitle){

if(!totalData || !totalData.length){
return null
}
const jsonObject = JSON.stringify(totalData)
const result = convertToCSV(jsonObject, headers)
if(!result){
return null
}
const blob = new Blob([result])
const exportedFileName = fileTitle? fileTitle+'.csv':'export.csv'
if(navigator.msSaveBlob){
navigator.msSaveBlob(blob, exportedFileName)
} else if (navigator.userAgent.match(/iPhone|iPad|iPod/i)){
const link = window.document.createElement('a')
link.href='data:text/csv;charset=utf-8,' + encodeURI(result);
link.target = "_blank"
link.download=exportedFileName
link.click()
} else {
const link = window.document.createElement('a')
if(link.download !== undefined){
const url = URL.createObjectURL(blob)
link.setAttribute("href", url)
link.setAttribute("download", exportedFileName)
link.style.visibility='hidden'
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
}
}
}

function convertToCSV(objArray, headers){
const columnDelimiter = ','
const lineDelimiter = '\r\n'
const actualHeaderKey = Object.keys(headers)
const headerToShow = Object.values(headers)
let str = ''
str+=headerToShow.join(columnDelimiter)
str+=lineDelimiter
const data = typeof objArray !=='object' ? JSON.parse(objArray):objArray
data.forEach(obj=>{
let line =''
actualHeaderKey.forEach(key=>{
if(line !=''){
line+=columnDelimiter
}
let strItem = obj[key] ? obj[key]+'': ''
line+=strItem? strItem.replace(/,/g, ''):strItem
})
str+=line+lineDelimiter
})
return str
}

Remove or Add Class on Button Click in LWC

 


removeOrAddClass.html
<template>
<div class="slds-hide slds-text-heading_small">Hello!!!!</div>
<lightning-button label="Show Div" onclick={handleClass}> </lightning-button>
</template>

removeOrAddClass.js

import { LightningElement } from 'lwc';

export default class RemoveOrAddClass extends LightningElement {
handleClass(){
const elmnt = this.template.querySelector('.slds-text-heading_small')
if(elmnt){
elmnt.classList.remove('slds-hide')
elmnt.classList.add('slds-text-color_error')
}
}
}

Tuesday, January 3, 2023

Use Lightning Design System Design Tokens in LWC

 

Design tokens are named entities that store visual design attributes, such as margins and spacing values, font sizes and families, or hex values for colors.

Use CSS variables in a Lightning web component to access Lightning Design System design tokens. Lightning web components can use any Lightning Design System design token marked Global Access.

designTokenInLWC.html

 <template>

<div>Design Token in LWC</div>

</template>

designTokenInLWC.js

import { LightningElement } from 'lwc';

export default class DesignTokenInLWC extends LightningElement {}

To reference a design token in your Lightning web component’s CSS, use the --lwc- prefix and reference the token name in camelCase
/* myWebComponent.css */
div {
    margin-right: var(--lwc-spacingSmall);
}

designTokenInLWC.css

  div{

color:var(--lwc-brandAccessible);

background:var(--lwc-colorBackgroundAlt);
}


Dynamic CSS in LWC

 



dynamicCss.html

  <template>

<lightning-card title="Dynamic CSS">
<div class="slds-var-m-around_medium">
<lightning-input type="number" value={currentVal} label="Percentage"
onkeyup={changeHandler}></lightning-input>
<div style={show} class="slds-notify slds-notify_alert
slds-theme_alert-texture slds-theme_error" role="alert">
Hey!!!
</div>
</div>
</lightning-card>

</template>

dynamicCss.js

import { LightningElement } from 'lwc';

export default class DynamicCss extends LightningElement {
currentVal = 10;
changeHandler(event){
this.currentVal = event.target.value;
}
get show(){
return `width:${this.currentVal}%`;
}
}