Tuesday, November 12, 2019

How to get Record Id and Object Name into Lightning Web Component(lwc)

We used the force:hasRecordId interface to a Lightning component to enable the component to be assigned the ID of the current record. The current record ID is useful if the component is used on a Lightning record page.

We used the force:hasSObjectName interface to a Lightning component to enable the component to be assigned the API name of the current record’s sObject type. The sObject name is useful if the component can be used with records of different sObject types.

To get the record id and sObjectName in Lightning web components we can use the public decorate '@api'
@api recordId;
@api objectApiName;

HTML Code
<template>
    <lightning-card>
        <div class="slds-text-heading_medium slds-text-align_center">
            Record Id : {currenRecordId}
        </div>
        <div class="slds-text-heading_medium slds-text-align_center">
            Object Name : {currenObjectName}
        </div>
    </lightning-card>
</template>

Javascript Controller
import { LightningElement, api, track } from 'lwc';

export default class LWCDemo extends LightningElement {
    @api objectApiName;
    @api recordId;
    @track currenObjectName;
    @track currenRecordId;

    connectedCallback() {
        this.currenRecordId = this.recordId;
        this.currenObjectName = this.objectApiName;
    }
}
Configuration File
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" fqn="LWCDemo">
    <apiVersion>46.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__RecordPage</target>
    </targets>
</LightningComponentBundle>

Output

2 comments:

  1. Hello, trying to figure out why you're using a connected call back. Why doesn't the component just render the object without a re-render?

    ReplyDelete