[SalesForce] Lightning Web Component: Navigation on Button-Click

I am attempting to navigate when a button-click occurs in lightning. Nothing happens when I click the button. Any thoughts on how to make this work? Code sample included:

import { LightningElement, track } from 'lwc';
   import { NavigationMixin } from 'lightning/navigation';

   export default class CreateNewTSSCaseButton extends 
   NavigationMixin(LightningElement) {
    connectedCallback()
    {
        // Opening
        console.log("connectedCallback.Start");

        // Navigate to Account Page
        this.accountHomePageRef = {
            type: "standard__objectPage",
            attributes: {
                "objectApiName": "Account",
                "actionName": "home"
            }
        };
        this[NavigationMixin.GenerateUrl](this.accountHomePageRef)
            .then(url => this.url = url);

        // Closing
        console.log("connectedCallback.Finish");
    }
    AddTSSCase_Click() {

        // Opening
        console.log("AddTSSCase_Click.Start");

        // Perform navitation
        console.log(this.accountHomePageRef);
        this[NavigationMixin.GenerateUrl](this.accountHomePageRef)
            .then(url => this.url = url);

        // Closing
        console.log("AddTSSCase_Click.Finish");
    }
   }

BTW, I am getting all Console.log messages in the Console window, so AddTSSCase_Click is firing.

Best Answer

You should either use href of anchor tag to go to url or you should use Navigate method of mixin.

Option 1: Using Navigate: (recommended)

HTML:

<div>
    <lightning-button label="Acc Home" onclick={AddTSSCase_Click}></lightning-button>
</div>

JS:

AddTSSCase_Click() {
    this[NavigationMixin.Navigate]({
        type: 'standard__objectPage',
        attributes: {
            objectApiName: 'Account',
            actionName: 'home'
        }
    });
}

Option 2: Using href:

You have already stored url in connectedCallback. Now use it in HTML as below:

<div>
    <a href={url} class="slds-button slds-button_brand" target="_blank">Go to acc home</a>
</div>

JS: You have to make url tracked so that it reflect in HTML when it gets the value:

@track url;
connectedCallback() {
    this[NavigationMixin.GenerateUrl]({
        type: 'standard__objectPage',
        attributes: {
            objectApiName: 'Account',
            actionName: 'home'
        }
    }).then((url) => (this.url = url));
} 

ideally you should also use catch.

Related Topic