In Lightning Web component, we can create component with and without HTML template. Component without HTML template is called Service Component or Service Libraries. Service Component can be created for reusable functions, which can be used in other LWC component.
This post will explain how we can create Service Component which will be used in other component. This component has below functions.
- LOGO_URL – Which wll provide Logo Url for application
- showMessage – This function will show toast message.
- isValidForm – This function will check validity of each field on page
- validateEmail – This function will validate Email
- validateDOB – This function will validate that Date of Birth is not a future date
We can add more functions based on our requirement.
As these function should be accessible in other components, we have to export these functions.
export { showMessage, isValidForm, LOGO_URL, validateEmail, validateDOB }
This service component is ready to be used in another LWC component. Let us create one LWC component to insert new employee in Salesforce Employee object. I have only consumed service component function and not written code for actual record insertion for this blog.
For using above service component we have to import that component.
import { showMessage, isValidForm,validateEmail,validateDOB} from 'c/commonLib';
and we can call service component function like normal function.
showMessage(this,'Notification',message,'error');
Complete Code For using Service Component
Benefit of Service Component
- Easy and Less Maintainable Code
- Code Re-usability
- Better Code Practice
- Separation of common and single requirement code
Demo Page:
Here is screenshot for showMessage function when required fields are not provided.
Reference:
2 comments
That was really helpful. Thank you very much.
Thank You Tomasz.