I am new to Lightning Web Components. I have made a component that searches contacts. I displayed recordId, name and email of the contacts. I have placed the component on the lead record page. I want to navigate to a particular contact by clicking on it from the result obtained.
I prepared a lightning card for each displayed contact and implemented an onClick method. In onclick method, I used this.recordId
for navigation. It's taking me to the lead record page again. How can I use the contactId
to navigate to the contact record page by clicking on the respective card? I searched for solution but didn't find any.
Apex Method:
@AuraEnabled(cacheable=true)
public static list<sObject> getContactList(String name){
String key = '%'+name+'%';
String query = 'Select Id,Name,Email,Phone From Contact Where Name LIKE :key LIMIT 10';
return Database.query(query);
}
HTML File:
<template>
<lightning-card >
<div class="slds-m-around_medium"><h1>Search Contacts(communicate with apex)</h1></div>
<div class="slds-m-around_medium">
<lightning-input label="Find Contact" value={searchKey} onchange={handleChange} class="slds-m-bottom_small">
</lightning-input>
<template for:each={contacts} for:item="contact">
<lightning-layout-item key={contact.key}>
<lightning-card onclick={navigateToContact} variant="narrow">
<c-contact-card slot="footer" key={contact.id} contact1={contact} ></c-contact-card>
<!-- the above component is used for printing id, name and email -->
</lightning-card>
</lightning-layout-item>
</template>
</div>
</lightning-card>
</template>
JS Function:
navigateToContact() {
// View a custom object record.
this[NavigationMixin.Navigate]({
type: 'standard__recordPage',
attributes: {
recordId: this.recordId,
objectApiName: 'contact', // objectApiName is optional
actionName: 'view'
}
});
}