Sunday, December 20, 2020

How to get record id in lightning web component?

 In this blog post we will learn "How to get record id in lightning web component?".

By using force:hasRecordId interface in Aura component we can get the id of the current record however in LWC it is very easy to get the id of the current record.

In the component’s JavaScript class, we use @api decorator to create a public recordId property as shown below.


import { LightningElement, api } from 'lwc';

export default class TestClass extends LightningElement {

    @api recordId;

}

When our component is invoked in a record context, recordId is set to the 18-character ID of the record.

If we are going to use the lightning web component in lightning record page we will have to expose the component in meta file as shown below.


Let us understand with an example:


I have created the lightning web component and placed it on Account record page.


recordDetailCheckComp.html


<template>

    <div>

        Record Id is : {recordId}

    </div>

</template>


recordDetailCheckComp.js


import { LightningElement,api } from 'lwc';

 

export default class RecordDetailCheckComp extends LightningElement {

 

    @api recordId;

 

}


recordDetailCheckComp.js-meta.xml


<?xml version="1.0" encoding="UTF-8"?>

<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">

    <apiVersion>50.0</apiVersion>

    <isExposed>true</isExposed>

    <targets>

        <target>lightning__RecordPage</target>

    </targets>

</LightningComponentBundle>


Output:


How to get record id in lightning web component?


1 comment:

  1. This comment has been removed by a blog administrator.

    ReplyDelete