Showing posts with label LWC. Show all posts
Showing posts with label LWC. Show all posts

Sunday, March 8, 2020

Wednesday, October 9, 2019

Sunday, August 18, 2019

LWC: Implementing Service Components


A service component is a component that provides an API for a set of functionalities. Ideally, the service should be specialized, generic and reusable. Also, it does not have a markup, i.e. it is not visible by default.

Creating a custom service simplifies component’s code and help reduce code duplication. This in turns makes the code more robust and facilitates maintenance.

To develop a custom service component for my Account object, I have created an accountService component and exposed the below services:
  • searchAccount: it accepts a search key and returns the list of accounts matching the key
  • getAccounts: this returns a list of 5 accounts

You will notice that I have followed the singleton pattern to define this component, i.e. there can be only one instance of this component. Now to get a reference to these custom services, I have created an accountComponent which is consuming the services like below:

Please see the below repo for the code:
https://github.com/iamsonal/lwc-service

References:
https://developer.salesforce.com/blogs/2018/08/implement-and-use-lightning-service-components.html
Share This:    Facebook Twitter

Saturday, August 17, 2019

LWC: Modularizing Code using Singleton pattern


Imagine that we have a custom LWC component, which we drag-and-drop onto a Lightning page in Lightning App Builder. This component has 2 design attributes for First Name and Last Name. We need a way to access these values from any component without communicating down the containment hierarchy. Setting the public properties of child components becomes a tedious job if there are nested components.

To solve this issue, we can use the Singleton Pattern, which states that the number of instances of an object must be restricted to one only, hence the "single" in Singleton. The intent of the Singleton is ensuring a class has only one instance, and providing a global point of access to it.

For the sake of simplicity, I have created 2 components component1 and component2 where component2 is the child of component1. I need to access the design attribute values of the parent component from the child component. In this example, we are storing the design attribute values in a single central place, sharedData component, written in the Singleton pattern.

which can be accessed by any component in the application like below:

Similarly, to get one point of access to custom labels, I have created a component customLabels using Javascript classes to access the custom labels

To know more about Object.freeze(), refer one of my post titled Javascript: Preventing Object Modification. Now any component in the application can access these values like below:


Please see the below repo for the code:
https://github.com/iamsonal/lwc-singleton

Share This:    Facebook Twitter

Saturday, August 10, 2019

LWC: Modal implementation



Check the code in the below repo for the modal implementation in LWC:
https://github.com/iamsonal/lwc-modal

Notes:
  • If you want to hide the close icon, then set the hide-close property to true like below:

  • <!-- modalContainer.html -->
    <template>
        <c-modal name="Modal Name" title="Modal Title" hide-close>
        </c-modal>
    </template>

  • Similarly, if you want to display a large modal, then set the is-large property to true like below:

  • <!-- modalContainer.html -->
    <template>
        <c-modal name="Modal Name" title="Modal Title" hide-close is-large>
        </c-modal>
    </template>


  • Using slots (unnamed and named), we are passing the modal body and footer content from parent into the child component like below. In this way, we can control the markup that can be displayed in the modal. For more information about how to use slots, check the LWC documentation.

  • <c-modal name="Modal Name" title="Modal Title" >
    
        <!-- Unnamed Slot -->
        <p>This is some content</p>
    
        <!-- Named Slot -->
        <div slot="footer" style="display: inline;">
            <lightning-button label="Close" variant="neutral" onclick={handleCancelModal}></lightning-button>
        </div>
        
    </c-modal>


  • Set the style-class property to apply a custom CSS in the modal.

Share This:    Facebook Twitter

Saturday, July 13, 2019

LWC: Override CSS of standard Lightning Web Components

Recently, I got a requirement where I had to override the CSS of lightning-card component, specifically to change the background colour of the header of the card component.

Shadow Dom have their own little kingdom and cannot be styled from outside, except if they would provide some options to do so. Currently, it's not possible to style standard Lightning Web Components;

I am providing a hacky workaround to get the desired results. I added the below code in my helloExpressions component:
renderedCallback() {
    const style = document.createElement('style');
    style.innerText = `c-hello-expressions .slds-card__header {
    background-color: #54C2B2;
    }`;
    this.template.querySelector('lightning-card').appendChild(style);
}

and this is how it looks:

UPDATE:
It seems there is a cleaner approach as suggested by pdebaty: loading CSS using loadStyle...lol. You can go through the StackExchange article to understand more in details.


Share This:    Facebook Twitter

Monday, March 4, 2019

LWC: Fetch picklist values

<!-- fetchPicklistValues.html -->
<template>
    <lightning-card title="WireGetPicklistValues" icon-name="custom:custom67">
        <template if:true={picklistValues.data}>
            <div class="slds-m-around_medium">
                <template for:each={picklistValues.data.values} for:item="item">
                    <lightning-input
                        key={item.value}
                        label={item.label}
                        data-value={item.value}
                        type="checkbox"
                        onchange={handleCheckboxChange}
                    ></lightning-input>
                </template>
            </div>
        </template>
    </lightning-card>
</template>


// fetchPicklistValues.js
import { LightningElement, wire } from 'lwc';
import { getPicklistValues } from 'lightning/uiObjectInfoApi';
import TYPE_FIELD from '@salesforce/schema/Account.Type';

import { getObjectInfo } from 'lightning/uiObjectInfoApi';
import ACCOUNT_OBJECT from '@salesforce/schema/Account';

export default class FetchPicklistValues extends LightningElement {

    @wire(getObjectInfo, { objectApiName: ACCOUNT_OBJECT })
    objectInfo;

    @wire(getPicklistValues, {
        recordTypeId: '$objectInfo.data.defaultRecordTypeId',
        fieldApiName: TYPE_FIELD
    })
    picklistValues;

    handleCheckboxChange(event) {
        console.log(event.target.dataset.value);
        console.log(event.target.checked);
    }
}

As per documentation, use getPicklistValues wire adapter (from lightning/uiObjectInfoApi module) to fetch picklist values for a specified field.

Parameters:

  • recordTypeId—(Required) The ID of the record type. Use the Object Info defaultRecordTypeId property, which is returned from getObjectInfo or getRecordUi.
  • fieldApiName—(Required) The API name of the picklist field on a supported object.
  • propertyOrFunction—A private property or function that receives the stream of data from the wire service. If a property is decorated with @wire, the results are returned to the property’s data property or error property. If a function is decorated with  @wire, the results are returned in an object with a data property and an error property.
Find out more about the data inside objectInfo and picklistValues variable:


Share This:    Facebook Twitter

Sunday, March 3, 2019

Lightning Web Components: A Tale of Two DOM's


The shadow DOM is a subtree that branches off the DOM (light DOM). It hides away the complexity of components from the rest of the page. It has actually been around for quite a while. In fact, all of these elements utilize the shadow DOM to hide their complex markup and styling away.

<input type="range" />
<video controls width="250"></video>
<input type="date" />

Because of the new concept of shadow DOM, we need to avoid the confusion between the DOM you knew before and this new shadow DOM. So you are going to see the term light DOM used to describe the DOM you have been familiar with and working with all these years. But before we dive into the shadow DOM, here's one more term, the logical DOM. So the logical DOM is an umbrella term, so the light DOM and shadow DOM together are a part of logical DOM.


To understand shadow DOM, let’s look at the HTML5 <video> element, which is a custom element with a shadow DOM. Because Show user agent shadow DOM is enabled in Chrome Developer Tools, you see the #shadow-root node and its child elements, which make up the shadow DOM. If you disable this option, you would see only the <video> tag, and none of its children.


There are a variety of terms that we need to understand when working with the shadow DOM.
  • Shadow Host: It is the element in the light DOM that is hosting the shadow DOM. So the shadow host, in this case, is the video tag, and it hosts the shadow root.
  • Shadow Root: It is labelled in Chrome dev tools with #shadow-root, and is the root node of the shadow tree, encapsulating a DOM subtree. All this markup within the shadow root is shadow DOM. You can also see a nested shadow tree here, which is also known as a DOM subtree. So one DOM subtree can end up hosting another DOM subtree
  • Shadow Boundary: It encapsulates styling rules that are defined within a given piece of shadow DOM. So in other words, a CSS selector that's applied in the shadow DOM doesn't apply to other elements outside of shadow DOM and vice versa. This is because styles in the shadow DOM do not cross over the shadow boundary. The shadow boundary exists at the shadow root. To clarify, the shadow boundary is a concept and is merely a term used to describe the boundary between the light DOM and shadow DOM.
Creating shadow DOM is a simple 3-step process.
  1. Select shadow host, which is an element in the light DOM that will wrap the shadow root.
  2. Create a shadow root
  3. Add elements to the shadow DOM using the same methods that you use to append elements to the light DOM: innerHTML and appendChild
In the code below, the style is only going to impact the light DOM.

<!DOCTYPE html>
<html lang="en">
<head>
    <style>
        h1 { color: red; }
    </style>
</head>
<body>
    <h1>Hello World from the light DOM</h1> 
    <div id="host"></div>

    <template>
        <h1>Hello World from the shadow DOM</h1>
    </template>

    <script>
        var template = document.querySelector('template');
        var host = document.getElementById('host');
        var root = host.attachShadow({mode: 'open'});
        root.appendChild(document.importNode(template.content, true));

        // Only going to get a reference to the light DOM
        console.log(document.querySelectorAll('h1'));

        // Only going to get a reference to the shadow DOM. For multiple pieces of shadow DOM in the page,
        // you need to get the shadow root that is appropriate for the element that you are trying to target
        console.log(root.querySelectorAll('h1'));
    </script>
</body>
</html>

Lightning Web Components

The shadow DOM for a Lightning web component is created automatically. The component author doesn’t have to implement it (no need to use the attachShadow() or appendChild() methods). Also since Lightning web components don’t use the native shadow DOM yet, you can’t view their shadow DOM in Chrome Developer Tools. Even if you enable Show user agent shadow DOM, you don’t see the shadow DOM.

Resources:
https://medium.com/front-end-weekly/the-rise-of-shadow-dom-84aa1f731e82
Share This:    Facebook Twitter

Total Pageviews

My Social Profiles

View Sonal's profile on LinkedIn

Tags

__proto__ $Browser Access Grants Accessor properties Admin Ajax AllowsCallouts Apex Apex Map Apex Sharing AssignmentRuleHeader AsyncApexJob Asynchronous Auth Provider AWS Callbacks Connected app constructor Cookie CPU Time CSP Trusted Sites CSS Custom settings CustomLabels Data properties Database.Batchable Database.BatchableContext Database.query Describe Result Destructuring Dynamic Apex Dynamic SOQL Einstein Analytics enqueueJob Enterprise Territory Management Enumeration escapeSingleQuotes featured Flows geolocation getGlobalDescribe getOrgDefaults() getPicklistValues getRecordTypeId() getRecordTypeInfosByName() getURLParameters Google Maps Governor Limits hasOwnProperty() Heap Heap Size IIFE Immediately Invoked Function Expression Interview questions isCustom() Javascript Javascript Array jsForce Lightning Lightning Components Lightning Events lightning-record-edit-form lightning:combobox lightning:icon lightning:input lightning:select LockerService Lookup LWC Manual Sharing Map Modal Module Pattern Named Credentials NodeJS OAuth Object.freeze() Object.keys() Object.preventExtensions() Object.seal() Organization Wide Defaults Override PDF Reader Performance performance.now() Permission Sets Picklist Platform events Popup Postman Primitive Types Profiles Promise propertyIsEnumerable() prototype Query Selectivity Queueable Record types Reference Types Regex Regular Expressions Relationships Rest API Rest Operator Revealing Module Pattern Role Hierarchy Salesforce Salesforce Security Schema.DescribeFieldResult Schema.DescribeSObjectResult Schema.PicklistEntry Schema.SObjectField Schema.SObjectType Security Service Components Shadow DOM Sharing Sharing Rules Singleton Slots SOAP API SOAP Web Services SOQL SOQL injection Spread Operator Star Rating stripInaccessible svg svgIcon Synchronous this Token Triggers uiObjectInfoApi Upload Files VSCode Web Services XHR
Scroll To Top