Formatted Custom Label With Dynamic Input in LWC
This blog will help to manage formatted custom label with dynamic parameter in LWC with reusable service component. if we want to use a same custom label with different parameters then this will helpful. For example i have a custom label name is SelfInfo:-
My Self {0} i am a {1} |
in above custom label we can pass two parameters from java script.
dynamicCustomLabel.html:-
<template>
What about you:- {label}
</template>
dynamicCustomLabel.js
import { LightningElement, track } from 'lwc';
import Placeholder from '@salesforce/label/c.SelfInfo'; /*My Self {0} i am a {1}*/
import {showCustomLabel} from 'c/utils';
export default class DynamicCustomLabel extends LightningElement {
name = 'Mukesh gupta';
role = 'Technical Architect';
@track arr = [];
arr = ['Mukesh gupta','Technical Architect'];
get label(){
return showCustomLabel(Placeholder, this.arr);
}
}
dynamicCustomLabel.js-meta.xml
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>55.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__RecordPage</target>
<target>lightning__HomePage</target>
<target>lightning__AppPage</target>
</targets>
</LightningComponentBundle>
Also i have created a reusable Service Component () that’s will import in above component
utils.js:-
const showCustomLabel = (stringToFormat,formattingArgumt) => {
console.log('stringToFormat===>>> '+stringToFormat);
console.log('formattingArgumts===>>> '+formattingArgumt);
if (typeof stringToFormat !== 'string') throw new Error('\'stringToFormat\' must be a String');
return stringToFormat.replace(/{(\d+)}/gm, (match, index) =>
(formattingArgumt[index] === undefined ? '' : `${formattingArgumt[index]}`));
}
export{
showCustomLabel
}
utils.js-meta.xml:-
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>55.0</apiVersion>
<isExposed>false</isExposed>
</LightningComponentBundle>
Output:-