Sometimes, on click of button, to navigate another component in lightning web components. we can do this with the help of NavigationMixin service. we can also pass data from lwc component 1 to component 2.
Navigate and Pass Data from one lwc to another lwc
Here is sample LWC component, navigating from NavComponentOne to NavComponentTwo.
NavComponentOne.html
<template>
<lightning-button label="Navigate to another component" onclick={handleNavigation}></lightning-button>
</template>
NavComponentOne.js
import { LightningElement } from 'lwc';
import {NavigationMixin} from 'lightning/navigation';
export default class NavComponentOne extends NavigationMixin(LightningElement) {
handleNavigation(){
let compDef = {
componentDef: 'c:navComponentTwo',
// if you want to pass any data
attributes: {
testVar : 'World'
}
}
let encodedDef = btoa(JSON.stringify(compDef));
this[NavigationMixin.Navigate]({
type: "standard__webPage",
attributes: {
url: "/one/one.app#"+encodedDef
}
})
}
}
NavComponentOne.js-meta.xml
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>57.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__AppPage</target>
<target>lightning__RecordPage</target>
</targets>
</LightningComponentBundle>
from here component 2 code starts.
NavComponentTwo.html
<template>
<h1>Hello {testVar}</h1>
</template>
NavComponentTwo.js
import { LightningElement ,api} from 'lwc';
export default class NavComponentTwo extends LightningElement {
@api testVar;
}
NavComponentTwo.js-meta.xml
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>57.0</apiVersion>
<isExposed>false</isExposed>
</LightningComponentBundle>
Output screenshot:
Also found above code in Tech Shorts Git repo
Source:
https://developer.salesforce.com/docs/platform/lwc/guide/use-navigate-basic.html