How to open URL in new tab on click in LWC using NavigationMixin

NavigationMixin is supported and used to navigate in Lightning Experience, Salesforce Communities, and Salesforce App. Instead of a URL, navigation services use a page reference, which describes the page.


Let's see an example of Navigation Services usage in LWC: 

Navigation Services in LWC:

NavigationMixinExample.html
<template>
<lightning-card>
<table class="slds-table slds-table_cell-buffer slds-table_bordered">
<thead>
<tr class="slds-line-height_reset">
<th scope="col">Index</th>
<th scope="col">Name</th>
</tr>
</thead>
<tbody>
<tr class="slds-hint-parent" for:each={Accounts} for:item="account" key={account.Id}>
<td scope="col">{account.index}</td>
<td scope="col">
<a href="#" onclick={handleNavigate} data-id={account.accData.Id}>
{account.accData.Name}
</a>
</td>
</tr>
</tbody>
</table>
</lightning-card>
</template>

NavigationMixinExample.js
import { LightningElement,wire } from 'lwc';
import { NavigationMixin } from "lightning/navigation";
import fetchAllAccounts from '@salesforce/apex/NavigationMixinExampleController.fetchAllAccounts';
export default class NavigationMixinExample extends NavigationMixin(LightningElement) {
Accounts;
@wire(fetchAllAccounts)
wiredac({ error,data }) {
if (data) {
this.Accounts = this.data = data.map((Obj, index) => ({
accData: { ...Obj },
index: index + 1
}));
} else if (error) {
console.log('An error has occurred:', error);
this.Accounts = false;
// handle your error.
}
}
handleNavigate(event) {
var accId = event.target.dataset.id;
this[NavigationMixin.GenerateUrl]({
type: "standard__recordPage",
attributes: {
recordId: accId,
actionName: "view"
}
}).then(url => {
window.open(url, "_blank");
});
}
}

NavigationMixinExample.js-meta.xml
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>54.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__HomePage</target>
</targets>
</LightningComponentBundle>

Related Apex Class:

NavigationMixinExampleController.cls
public with sharing class NavigationMixinExampleController {
@AuraEnabled
public static List<Account> fetchAllAccounts(){
List<Account> accList = [SELECT Id,Name From Account ORDER BY Name LIMIT 10];
return accList;
}
}
Let see it in action:

Comments