Tag:

lwc

    Inheritance in Lightning Web Component

    Lightning Web Component is new Salesforce development framework which is based on current Web Standards. We can utilize all features of web standards in our lightning web component. In this blog we will cover one of requirement which is very basic for all lightning community.

    Use Case / Requirement
    We have requirement that, We need to show current user detail on Portal Header. This current user detail can be accessed by other component as well for referring current user information.

    Solution
    As we need to show user detail on other components, so we can create global module or class inheritance. Class Inheritance is important feature of ES6+.

    Let us resolved this task as class inheritance.

    1. Create BaseElement component in your LWC Project.

      import { LightningElement,api } from 'lwc';
      
      export default class BaseElement extends LightningElement {
          @api
          get currentCustomerName() {
              return sessionStorage.getItem("name");
          }
      
          set currentCustomerName(value) {
              sessionStorage.setItem("name",value);
          }
      }
      

      We have used sessionStorage API of window class. This api is used to store information in session, so that value will be accessible in all component in current user session.

    2. Create DerivedElement component in your LWC Project.

      import { track } from 'lwc';
      import BaseElement from 'c/baseElement';
      export default class DerivedElement extends BaseElement {
          //currentCustomerName is declared in base Element
          @track customerName=this.currentCustomerName;
      }
      

      We have inherited derivedElement from BaseElement class. All methods and properties of baseElement will be accessible in derived elements.

    April 11, 2019 4 comments
    1 Facebook Twitter Google + Pinterest