Navigation in LWC
Navigation in LWC :
There are a few steps to navigate from LWC :
- import {NavigationMixin } from ‘lightning/navigation;
- Apply the navigationMixin to the component’s base class to gain access t its APIs.
- export default class NavigationExample extends NavigationMixin (Lightning element)
- NavigationMixin has two methods :
- Navigate
- GenerateURL
Limitations of NavigationMixin :
Lightning Navigation doesn’t work if we are using LWC
- inside visualforce page.
- inside aura component.
We will see one example of Navigate, let’s create a component to navigate to the record detail page from LWC.
ContactCreateForm.html:
<template> <lightning-card> <lightning-record-form object-api-name={objectApiName} fields={fields} onsuccess={handleSuccess}> </lightning-record-form> </lightning-card> </template>
ContactCreateForm.js :
import { LightningElement } from 'lwc'; import { ShowToastEvent } from 'lightning/platformShowToastEvent'; import CONTACT_OBJECT from '@salesforce/schema/Contact'; import FIRST_NAME from '@salesforce/schema/Contact.FirstName'; import LAST_NAME from '@salesforce/schema/Contact.LastName'; import EMAIL_FIELD from '@salesforce/schema/Contact.Email'; import { NavigationMixin } from 'lightning/navigation'; export default class ContactCreator extends NavigationMixin (LightningElement) { objectApiName = CONTACT_OBJECT; fields = [FIRST_NAME, LAST_NAME, EMAIL_FIELD]; handleSuccess(event) { const toastEvent = new ShowToastEvent({ title: "Contact created", message: "Record ID: " + event.detail.id, variant: "success" }); this.dispatchEvent(toastEvent); this.navigateToNewContactPage(event.detail.id); } navigateToNewContactPage(contactId) { this[NavigationMixin.Navigate]({ type: 'standard__recordPage', attributes: { recordId: contactId, objectApiName: 'Contact', actionName: 'view' } }); } }
contactCreateForm.js-meta.xml :
<?xml version="1.0" encoding="UTF-8"?> <LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata"> <apiVersion>48.0</apiVersion> <isExposed>true</isExposed> <targets> <target>lightning__AppPage</target> <target>lightning__HomePage</target> <target>lightning__RecordPage</target> </targets> </LightningComponentBundle>