Get Record Id into Lightning Web Components

Let us discuss here how to get the current record id into the lightning web components.  If a component is used on a Lightning record page, you can pass the component the ID of the current record. In the component’s JavaScript class, use the @api decorator to create a public recordId property.

In this example, we will be using the lightning-record-view-form to show the record data. Let’s start with the simple lightning web component and then we will see another example of how to pass the record id to the apex controller from the lightning web component.

 Create a Lightning web component

Now create a lightning web component using the following SFDX command

Here is the RecordIdExample.html code and in this code, we are using the lightning-record-view-form to show the account data.

Here is the RecordIdExample.js controller. In this JavaScript class, use the @api decorator to create a public recordId property.

Sample RecordIdExample.css

Here is the RecordIdExample.js-meta.xml

Push Changes to Scratch Org 

Now push the changes from the local development to scratch org using this command

Add the lightning web component to the account record page using app builder and you can able to see the result as shown below.

 

 

Update code to pass record Id to Apex controller 

Let us make some changes now to the component. Now we will update the code in such a way that will get show the data for the selected account. Let us understand how to pass the record id to the apex controller here. create an apex class using this SFDX command

Here is the ContactData apex class.

Now update the RecordIdExample.html markup code as shown below

Now update the RecordIdExample.js controller as shown below. Now in this JavaScript controller, we are passing the current record id to apex controller and will get the data.

If you add the above component to the account record page, you can able to see the list of contacts related to the account as shown below.