Wednesday, July 7, 2021

How to navigate to record view page on button click lwc salesforce

 How to navigate to record view page on button click lwc salesforce

Solution: use the lightning-navigation service.The base class needs to extend NavigationMixin and then use methods to achieve this.

Example:

navigateToRecordViewPageLWC.html

<template>  

    <lightning-card title="Navigate To Record View Page On Click">  

      <div class="slds-p-around_small">  

        <ul class="slds-m-around_medium">

            <template for:each={lstAccount.data} for:item="account">

                <li key={account.Id} data-id={account.Id} onclick={navigateToRecordViewPage} style="color:blue; 

                text-decoration:underline;cursor:pointer; ">

                    {account.Name}

                </li>

            </template>

        </ul>

      </div>  

    </lightning-card>  

</template>  

navigateToRecordViewPageLWC.js

import { LightningElement,track,wire} from 'lwc';

import { NavigationMixin } from 'lightning/navigation';

import getAccounts from '@salesforce/apex/AccountController.getAccounts';

export default class NavigateToRecordViewPageLWC extends NavigationMixin(LightningElement) {

    @track lstAccount;

    @wire(getAccounts) wiredAccounts(data,error){

        if(data){

            this.lstAccount  = data;

            console.log(JSON.stringify(this.lstAccount));

        } else {

            console.log(error);

        }

    }

    navigateToRecordViewPage(event) {

        const selectedRecordId = event.target.dataset.id;

        console.log('Event',event);

        console.log('Event',selectedRecordId);

        this[NavigationMixin.Navigate]({

            type: 'standard__recordPage',

            attributes: {

                recordId: selectedRecordId,

                actionName: 'view',

            },

        });

    }

}

navigateToRecordViewPageLWC.js-meta.xml

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

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

    <apiVersion>51.0</apiVersion>

    <isExposed>true</isExposed>

    <targets>

        <target>lightning__RecordPage</target>

        <target>lightning__AppPage</target>

        <target>lightning__HomePage</target>

    </targets>

</LightningComponentBundle>

Output: