Create dynamic URL for a list of records in LWC

htmljavascriptlightning-web-components

I want to create dynamic URL for list of records in LWC component.

Scenario: I'm showing a list of opportunities based on the stage (closed won) in layout using LWC. When I click the opportunity name from the component page it should redirect to the opportunity record page and showing the details of the opportunity.

Problem: URL does not working when I click the opportunity Name

Here,I'm adding my code .anyone help me to sort out the problem.

Code:
JS

import { LightningElement ,api} from 'lwc';
import getOppty from '@salesforce/apex/OpptyController.getOppty';
import { NavigationMixin } from 'lightning/navigation';

export default class GetOpportunityRecord extends LightningElement {
    @api recordId;
    closedWon=[];
    oppty =[]; 
       connectedCallback(){
            this.getURLs() ;
            getOppty().then(result=>{
                for(let i=0; i<this.oppty.length; i++){
                    if(this.oppty[i].Stage === 'Closed Won'){
                        this.closedWon.push(this.oppty[i]);
                    }
                }
            }).catch(error=>{
                    console.error(error);
                });  
        }
        
        getURLs() {
            getOppty({opptyid : recordId}).then(result => {
                this.oppty = this.recordId;
                this.oppty = result;
            })
            .catch(error => {
                console.error(error);
            });
        }   
}

HTML:

<template>
    <lightning-card>
      <lightning-layout multiple-rows="true" >
       <template for:each={closedWon} for:item="opportunities"> 
          <lightning-layout-item key={opportunities.Id} size="3">
             <div class="custom-box slds-box  slds-text-align_center">
              <a href={getURLs} >
                <lightning-card icon-name="standard:Opportunity"  title={opportunities.Name}> 
                 </lightning-card>
              </a>
              <div class="slds-wrap">  
                 Account Name: {opportunities.AccountId}<br>
                 Stage : {opportunities.StageName}<br>
               </div> 
             </div>
          </lightning-layout-item>
       </template>
      </lightning-layout>
    </lightning-card>
</template>

Best Answer

You will have to use a combination of data-* attributes and the standard navigation event.

<a onclick={handleClick} data-oppid={opportunities.Id}>
...
</a>
handleClick(event){
    const recordId = event.target.dataset.oppid;
    this[NavigationMixin.Navigate]({
        type: 'standard__recordPage',
        attributes: {
            actionName: "view",
            recordId: recordId
        }
    });
}