Passing Current Object Name to Lightning Web Component
Lets us discuss here how to pass the current object name to the lightning web component. If a component is used on a Lightning record page, you can pass the component the API name of the current object. In the component’s JavaScript class, use the @api
decorator to create a public objectApiName
property. When your component is invoked in a record context in Lightning Experience or in the mobile app, the objectApiName is set to the API name of the object associated with the record being viewed, for example: Account
. The objectApiName
is set only when you place or invoke the component in an explicit record context. In all other cases, the objectApiName
isn’t set, and your component shouldn’t depend on it.
Create a lightning component
sfdx force:lightning:component:create --type lwc -n ViewObject -d force-app/main/default/lwc
Here is the ViewObject.html markup code
<template> <lightning-record-form record-id={recordId} object-api-name={objectApiName} layout-type="Full" mode="view"> </lightning-record-form> </template>
Here is the JavaScript controller class code .In the component’s JavaScript class, use the @api
decorator to create a public objectApiName
property and recordId property.
import { LightningElement ,api} from 'lwc'; export default class ViewObject extends LightningElement { @api objectApiName; @api recordId; }
Here is the ViewObject.js-meta.xml code
<?xml version="1.0" encoding="UTF-8"?> <LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata"> <apiVersion>45.0</apiVersion> <isExposed>false</isExposed> <targets> <target>lightning__RecordPage</target> </targets> </LightningComponentBundle>
Push the changes
Now push the changes to scratch org using the below SFDX command
sfdx force:source:push
Add this component to record page and you can able to see the output as shown below