Solution: There are many ways to do it.
1) Filtering the records directly in js file of LWC component
2) Passing parameter to Apex to fetch specified number of elements in query.
In this example we will do the filtering of records in js file.
Note: Custom Label is used to specify number of elements to show.
Example:
limitListIterationInLWC.html:
<template>
<lightning-card title="Limit List Interation in LWC">
<lightning-button label="Show More" data-labelname="more" title="Non-primary action" onclick={fetchRecords} class="slds-m-left_x-small"></lightning-button>
<lightning-button label="Show Less" data-labelname="less" title="Non-primary action" onclick={fetchRecords} class="slds-m-left_x-small"></lightning-button>
<div class="slds-p-around_small">
<template for:each={lstAccount} for:item="account" for:index="index">
<div class="slds-p-left_small" key={account.Id}>
{account.Name}
</div>
</template>
</div>
</lightning-card>
</template>
limitListIterationInLWC.js:
import { LightningElement ,track} from 'lwc';
import getAccounts from '@salesforce/apex/AccountController.getAccounts';
import NumberOfRecords from '@salesforce/label/c.Number_Of_Records_To_Display';
export default class LimitListIterationInLWC extends LightningElement {
@track lstAccount =[];
@track lstTempAccount;
@track noOfRecords = 0;
@track bMore = false;
connectedCallback() {
this.noOfRecords = NumberOfRecords;
getAccounts()
.then(result => {
if(result) {
this.lstTempAccount = result;
result.forEach((acc,index) => {
if(index <= this.noOfRecords) {
this.lstAccount.push(acc);
}
});
}
})
.catch(error => {
this.error = error;
});
}
fetchRecords(event) {
var lab = event.currentTarget.dataset.labelname;
if(lab == 'more') {
this.bMore = true;
} else {
this.bMore = false;
}
if(this.bMore == true) {
this.lstAccount = [];
this.lstTempAccount.forEach((acc) => {
this.lstAccount.push(acc);
});
} else {
this.lstAccount = [];
this.lstTempAccount.forEach((acc,index) => {
if(index <= this.noOfRecords) {
this.lstAccount.push(acc);
}
});
}
}
}
limitListIterationInLWC.js-meta.xml
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>54.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__RecordPage</target>
<target>lightning__AppPage</target>
<target>lightning__HomePage</target>
</targets>
</LightningComponentBundle>
Output:
No comments:
Post a Comment