Navigation Service in LWC(Lightning Web Components)

Navigation Service in LWC(Lightning Web Components)

Navigation Service in LWC(Lightning Web Components)

To navigate in Lightning Experience, Lightning Communities, and the Salesforce app, use the navigation service, lightning/navigation.

The lightning/navigation service is supported only in Lightning Experience, Lightning Communities, and the Salesforce app. It isn’t supported in other containers, such as Lightning Components for Visualforce, or Lightning Out. This is true even if you access these containers inside Lightning Experience or the Salesforce app. We can use navigation services in LWC to Navigate to Pages, Records, and Lists.

There are different types of navigation options available. Let’s discuss the basic one

Basic Navigation

Use the navigation service, lightning/navigation, to navigate to many different page types, like records, list views, and objects. Also use the navigation service to open files.

Instead of a URL, the navigation service uses a PageReference. A PageReference is a JavaScript object that describes the page type, its attributes, and the state of the page. Using a PageReference insulates your component from future changes to URL formats. It also allows your component to be used in multiple applications, each of which can use different URL formats.

Navigation service uses a PageReference. PageReference is a JavaScript object that describes the page type, its attributes, and the state of the page.

Page type(String) and attributes(Object) are required parameters, state(Object) is optional parameter.

Use Navigation Service in LWC

Here are steps to use the navigation service

  1. First, we need to import the lightning/navigation module.
    import { NavigationMixin } from 'lightning/navigation';
    
  2. Apply the NavigationMixin function to your component’s base class.
    export default class MyCustomElement extends NavigationMixin(LightningElement) {}
    
  3. Create a plain JavaScript PageReference object that defines the page
  4. To dispatch the navigation request, call the navigation service’s [NavigationMixin.Navigate](pageReference, [replace])
    navigateNext() {
           this[NavigationMixin.Navigate]({
               type: 'standard__navItemPage',
               attributes: {
                   apiName: this.tabName,
               },
           });
       }
    

The NavigationMixin adds two APIs to your component’s class. Since these APIs are methods on the class, they must be invoked with this reference.

  • [NavigationMixin.Navigate](pageReference, [replace]): A component calls this[NavigationMixin.Navigate] to navigate to another page in the application.
  • [NavigationMixin.GenerateUrl](pageReference): A component calls this[NavigationMixin.GenerateUrl] to get a promise that resolves to the resulting URL. The component can use the URL in the href attribute of an anchor. It can also use the URL to open a new window using the window.open(url) browser API.

 

Navigation Service in LWC Example

navigationExampleLWC.html

<template>
    <lightning-card title="Navigation Service in LWC(Lightning Web Components)">
        <lightning-card title="Navigate To Record Example">
            <lightning-button label="New Account" onclick={navigateToNewAccountPage}></lightning-button>
            <lightning-button label="View Account" onclick={navigateToViewAccountPage}></lightning-button>
            <lightning-button label="Edit Account" onclick={navigateToEditAccountPage}></lightning-button>
        </lightning-card>
        <lightning-card title="Navigate To Views">
            <lightning-button label="Account Recent list View" onclick={navigateToAccountListView}></lightning-button>
            <lightning-button label="Account Related List" onclick={navigateToContactRelatedList}></lightning-button>
        </lightning-card>
        <lightning-card title="Navigate To Home">
            <lightning-button label="Navigate to Home" onclick={navigateToHomePage}></lightning-button>
            <lightning-button label="Navigate to Contact Home " class="slds-m-around_medium" onclick={navigateToContactHome}></lightning-button>
        </lightning-card>
        <lightning-card title="Navigate To Other">
            <lightning-button label="Navigate to Chatter Home" onclick={navigateToChatter}></lightning-button>
            <lightning-button label="Navigate to Reports" onclick={navigateToReports}></lightning-button>
            <lightning-button label="Navigate to Tab" onclick={navigateToTab}></lightning-button>
            <lightning-button label="Navigate to SFDCPoint" onclick={navigateToWebPage}></lightning-button>
            <lightning-button label="Navigate to Files " class="slds-m-around_medium" onclick={navigateToFilesHome}></lightning-button>
        </lightning-card>
        <lightning-card title="Navigate To Component">
            <lightning-button label="Navigate to Visualforce page " onclick={navigateToVFPage}></lightning-button>
            <lightning-button label="Navigate to Aura Lightning Component " class="slds-m-around_medium" onclick={navigateToLightningComponent}></lightning-button>
        </lightning-card>
    </lightning-card>
</template>

navigationExampleLWC.js

import { LightningElement, api } from 'lwc';
import { NavigationMixin } from 'lightning/navigation';
export default class NavigationExampleLWC extends NavigationMixin(LightningElement) {
    @api recordId;
    // Navigate to New Account Page
    navigateToNewAccountPage() {
        this[NavigationMixin.Navigate]({
            type: 'standard__objectPage',
            attributes: {
                objectApiName: 'Account',
                actionName: 'new'
            },
        });
    }
    // Navigate to View Account Page
    navigateToViewAccountPage() {
        this[NavigationMixin.Navigate]({
            type: 'standard__recordPage',
            attributes: {
                recordId: this.recordId,
                objectApiName: 'Account',
                actionName: 'view'
            },
        });
    }
    // Navigate to Edit Account Page
    navigateToEditAccountPage() {
        this[NavigationMixin.Navigate]({
            type: 'standard__recordPage',
            attributes: {
                recordId: this.recordId,
                objectApiName: 'Account',
                actionName: 'edit'
            },
        });
    }
    // Navigation to Account List view(recent)
    navigateToAccountListView() {
        this[NavigationMixin.Navigate]({
            type: 'standard__objectPage',
            attributes: {
                objectApiName: 'Account',
                actionName: 'list'
            },
            state: {
                filterName: 'Recent'
            },
        });
    }
    // Navigation to Contact related list of account
    navigateToContactRelatedList() {
        this[NavigationMixin.Navigate]({
            type: 'standard__recordRelationshipPage',
            attributes: {
                recordId: this.recordId,
                objectApiName: 'Account',
                relationshipApiName: 'Contacts',
                actionName: 'view'
            },
        });
    }
    //Navigate to home page
    navigateToHomePage() {
        this[NavigationMixin.Navigate]({
            type: 'standard__namedPage',
            attributes: {
                pageName: 'home'
            },
        });
    }
    // Navigation to contant object home page
    navigateToContactHome() {
        this[NavigationMixin.Navigate]({
            "type": "standard__objectPage",
            "attributes": {
                "objectApiName": "Contact",
                "actionName": "home"
            }
        });
    }
    //Navigate to chatter
    navigateToChatter() {
        this[NavigationMixin.Navigate]({
            type: 'standard__namedPage',
            attributes: {
                pageName: 'chatter'
            },
        });
    }
    //Navigate to Reports
    navigateToReports() {
        this[NavigationMixin.Navigate]({
            type: 'standard__objectPage',
            attributes: {
                objectApiName: 'Report',
                actionName: 'home'
            },
        });
    }
    //Navigate to Files home
    navigateToFilesHome() {
        this[NavigationMixin.Navigate]({
            type: 'standard__objectPage',
            attributes: {
                objectApiName: 'ContentDocument',
                actionName: 'home'
            },
        });
    }
    // Navigation to lightning component
    navigateToLightningComponent() {
        this[NavigationMixin.Navigate]({
            "type": "standard__component",
            "attributes": {
                //Here customLabelExampleAura is name of lightning aura component
                //This aura component should implement lightning:isUrlAddressable
                "componentName": "c__customLabelExampleAura"
            }
        });
    }
    // Navigation to web page 
    navigateToWebPage() {
        this[NavigationMixin.Navigate]({
            "type": "standard__webPage",
            "attributes": {
                "url": "https://www.sfdcpoint.com/"
            }
        });
    }
    //Navigate to visualforce page
    navigateToVFPage() {
        this[NavigationMixin.GenerateUrl]({
            type: 'standard__webPage',
            attributes: {
                url: '/apex/AccountVFExample?id=' + this.recordId
            }
        }).then(generatedUrl => {
            window.open(generatedUrl);
        });
    }
    // Navigation to Custom Tab
    navigateToTab() {
        this[NavigationMixin.Navigate]({
            type: 'standard__navItemPage',
            attributes: {
                //Name of any CustomTab. Visualforce tabs, web tabs, Lightning Pages, and Lightning Component tabs
                apiName: 'CustomTabName'
            },
        });
    }
}

navigationExampleLWC.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__RecordPage</target>
        <target>lightning__HomePage</target>
    </targets>
</LightningComponentBundle>

Now we can add this LWC component on the Account Record page.

  • Go to Account detail record page
  • Click Setup (Gear Icon) and select Edit Page.
  • Under Custom Components, find your navigationExampleLWC component and drag it on right-hand side top.
  • Click Save and activate.

 

We will get the following output

Navigation Service in LWC

Navigate to New Record LWC

// Navigate to New Account Page
    navigateToNewAccountPage() {
        this[NavigationMixin.Navigate]({
            type: 'standard__objectPage',
            attributes: {
                objectApiName: 'Account',
                actionName: 'new'
            },
        });
    }

Navigate to View Record LWC

// Navigate to View Account Page
    navigateToViewAccountPage() {
        this[NavigationMixin.Navigate]({
            type: 'standard__recordPage',
            attributes: {
                recordId: this.recordId,
                objectApiName: 'Account',
                actionName: 'view'
            },
        });
    }

Navigate to the Edit Record LWC

// Navigate to Edit Account Page
    navigateToEditAccountPage() {
        this[NavigationMixin.Navigate]({
            type: 'standard__recordPage',
            attributes: {
                recordId: this.recordId,
                objectApiName: 'Account',
                actionName: 'edit'
            },
        });
    }

Navigate to List View LWC

// Navigation to Account List view(recent)
    navigateToAccountListView() {
        this[NavigationMixin.Navigate]({
            type: 'standard__objectPage',
            attributes: {
                objectApiName: 'Account',
                actionName: 'list'
            },
            state: {
                filterName: 'Recent'
            },
        });
    }

Navigate to Related List LWC

// Navigation to Contact related list of account
    navigateToContactRelatedList() {
        this[NavigationMixin.Navigate]({
            type: 'standard__recordRelationshipPage',
            attributes: {
                recordId: this.recordId,
                objectApiName: 'Account',
                relationshipApiName: 'Contacts',
                actionName: 'view'
            },
        });
    }

Navigate to Home Page LWC

//Navigate to home page
    navigateToHomePage() {
        this[NavigationMixin.Navigate]({
            type: 'standard__namedPage',
            attributes: {
                pageName: 'home'
            },
        });
    }

Navigate to Object Home LWC

// Navigation to contant object home page
    navigateToContactHome() {
        this[NavigationMixin.Navigate]({
            "type": "standard__objectPage",
            "attributes": {
                "objectApiName": "Contact",
                "actionName": "home"
            }
        });
    }

Navigate to Chatter Home LWC

//Navigate to chatter
    navigateToChatter() {
        this[NavigationMixin.Navigate]({
            type: 'standard__namedPage',
            attributes: {
                pageName: 'chatter'
            },
        });
    }

Navigate to Reports Tab LWC

//Navigate to Reports
    navigateToReports() {
        this[NavigationMixin.Navigate]({
            type: 'standard__objectPage',
            attributes: {
                objectApiName: 'Report',
                actionName: 'home'
            },
        });

Navigate to Files Home LWC

//Navigate to Files home
    navigateToFilesHome() {
        this[NavigationMixin.Navigate]({
            type: 'standard__objectPage',
            attributes: {
                objectApiName: 'ContentDocument',
                actionName: 'home'
            },
        });
    }

Navigate to Lightning Component LWC

// Navigation to lightning component
    navigateToLightningComponent() {
        this[NavigationMixin.Navigate]({
            "type": "standard__component",
            "attributes": {
                //Here customLabelExampleAura is name of lightning aura component
                //This aura component should implement lightning:isUrlAddressable
                "componentName": "c__customLabelExampleAura"
            }
        });
    }

Navigate to Web Page LWC

// Navigation to web page 
    navigateToWebPage() {
        this[NavigationMixin.Navigate]({
            "type": "standard__webPage",
            "attributes": {
                "url": "https://www.sfdcpoint.com/"
            }
        });
    }

Navigate to Visualforce page LWC

//Navigate to visualforce page
    navigateToVFPage() {
        this[NavigationMixin.GenerateUrl]({
            type: 'standard__webPage',
            attributes: {
                url: '/apex/AccountVFExample?id=' + this.recordId
            }
        }).then(generatedUrl => {
            window.open(generatedUrl);
        });
    }

Navigate to Custom Tab LWC

// Navigation to Custom Tab
    navigateToTab() {
        this[NavigationMixin.Navigate]({
            type: 'standard__navItemPage',
            attributes: {
                //Name of any CustomTab. Visualforce tabs, web tabs, Lightning Pages, and Lightning Component tabs
                apiName: 'CustomTabName'
            },
        });
    }

For more details please refer to official link.

Permanent link to this article: https://www.sfdcpoint.com/salesforce/navigation-service-in-lwc/

16 comments

Skip to comment form

    • Raj on June 2, 2020 at 6:52 pm
    • Reply

    Hi Ankur,

    While using navigateToWebPage, can i provide custom header attributes for the URL.
    The URL will be a dynamic web page.
    X-Bearer-Token
    X-Refresh-Token etc ?

    • Deepak on June 6, 2020 at 3:08 am
    • Reply

    There is no examples for navigation between community pages but its mentioned in points. And I tried to achieve the navigation as per lwc developer guide. but still could not achieve that.

    • carlo on June 9, 2020 at 7:25 pm
    • Reply

    Hi Ankush,
    Thanks for this guide, do you know if is possible to navigate to a Lightning web component too?
    Thasnk,
    Carlo.

    • Asif Jamal on July 4, 2020 at 4:01 pm
    • Reply

    Requirment- vertical tab with dynamic icon. when ever user is authorised then tab is approved and icon udaate x cros to \/ aprroved symble.

    I am using above funtionality but how render a component whenever select any tab(Navigation Label).

    • subbu on August 20, 2020 at 7:10 pm
    • Reply

    i tried it is not working

    • PREETAM DUBEY on October 12, 2020 at 11:06 pm
    • Reply

    If i want to build something like one LWC component where i can take input from user(let say amount ) and than one button -on click it will navigate to account record page and there i want to use that amount in some text field .

    How we will do .

    While navigating how to pass the data as well ,like in vf we will pass via url

    • Rama on November 3, 2020 at 10:52 pm
    • Reply

    Can you please help me whenever clicking links in email template we need to navigate record age mobile app.
    2. In lwc or aura when ever click any button it will navigate record page in mobile app.

    • Shubam on November 6, 2020 at 12:00 pm
    • Reply

    can you tell me if there are record types of account so while creating the new Account Record How it will ask for ‘Select Record Type’

    • Venkata on December 2, 2020 at 8:04 am
    • Reply

    Hi Ankush,

    COuld you help me to invoke a LWC from another LWC on the same page.

    I am using below but it is rendering on a different tab. I need that on the same page.

    var compDetails ={
    compDef: “c:populateLwc”, (THis is the name of the another LWC which i want to open)
    attributes:{
    propertyvalue:”500″
    }
    };
    var encodedCompDetails = btoa(JSON.stringify(compDetails);
    this[NavigationMixin.Navigate](
    {
    type: ‘standard_webPage’,
    attributes :{
    url:’/one/one.app#’+ encodedCompDetails;
    }
    }

      • siva on January 27, 2022 at 7:01 am
      • Reply

      Venkat, even me too having same issue..please let me know if any other workaround sollution

    • Rishabh Tiwari on July 29, 2021 at 4:25 pm
    • Reply

    Hi Ankush,

    I have used navigate to Visualforce Page in my component but there is an issue with the Android application in Saleforce1. It is redirecting to the webpage and asking for username password while it is working perfectly in iOS.
    Could you help me with this.

    Thanks

    • vijay on August 6, 2021 at 1:55 pm
    • Reply

    is there any way we can make tabs (likedetail or related or any other tab under a record) as default.

    Please help.

    Thanks

    • sonam dewangan on August 30, 2021 at 1:56 pm
    • Reply

    Great!!

    • BusSchedule on December 29, 2021 at 12:40 pm
    • Reply

    hi
    import { LightningElement,api } from ‘lwc’;
    import { NavigationMixin } from ‘lightning/navigation’;
    export default class AccountNav extends NavigationMixin (LightningElement) {
    @api recordId;
    // Navigate to Edit Account Page
    navigateToEditAccountPage() {
    this[NavigationMixin.Navigate]({
    type: ‘standard__navItemPage’,
    attributes: {
    recordId: this.recordId,
    objectApiName: ‘Account’,
    actionName: ‘edit’
    },

    });
    }
    }
    i use this code but after that its not navigate the edit page .error will shown .
    Enter a valid URL and try again

    • arpita on March 24, 2022 at 9:58 pm
    • Reply

    I am getting deployment error for .js file I i am using following code in js
    import { LightningElement } from ‘lwc’;

    export default class Navigation extends LightningElement {

    navigateToWebPage() {
    this[NavigationMixin.Navigate]({
    “type”: “standard__webPage”,
    “attributes”: {
    “url”: “https://www.sfdcpoint.com/”
    }
    });
    }
    }

    • Mohsina on June 6, 2023 at 3:36 pm
    • Reply

    Is there a way to identify navigation to other tab from one tab.can you please help

Leave a Reply

Your email address will not be published.