How to navigate from one lightning component to another Lightning component

  • I am new to salesforce Lightning component and I meet a problem about how to navigate from one lightning component to another Lightning component,I want to know what is the best practise for it?

    Now I just build a desktop app, in one component named studys I have a button and when I click the button I want to show the studyDetail component, and the studys component is not on the page.

    How can I do this?

  • You need three components in total, lets say my third component studysMainCmp and is as below.

    <aura:component access="global" implements="force:appHostable">
        <aura:handler name="init" value="{!this}" action="{!c.doInit}" />
        <aura:handler event="c:navigateToCmp" action="{!c.NavigateComponent}" />
    
        <div>
            {!v.body}
        </div>
    </aura:component>
    

    Controller:

    doInit : function(component, event, helper) {
        $A.createComponent("c:studys", {
    
        }, function(newCmp) {
            if (component.isValid()) {
                component.set("v.body", newCmp);
            }
        });
    },
    
    NavigateComponent : function(component, event, helper) {
    if(event.getParam("navigate") == "true")
    {
        $A.createComponent("c:studyDetail", {
    
            }, function(newCmp) {
                if (component.isValid()) {
                    component.set("v.body", newCmp);
                }
            });
    }
    }
    

    In your study component the button action should fire an event, the button function will be as below

    buttonFunction : function(component, event) {
        var event = $A.get("e.c:navigateToCmp");
        event.setParams({
            "navigate" : "true"
        });
        event.fire();
    },
    

    Lightning event named navigateToCmp will be as below:

    <aura:event access="global" type="APPLICATION" description="Event template" >
        <aura:attribute name="navigate" type="Boolean" default="false"/>
    </aura:event>
    

    Please follow the blog https://force-base.com/2016/01/04/how-to-navigate-from-one-component-to-another-in-lightning/

    It worked for me, hope it helps for you.

License under CC-BY-SA with attribution


Content dated before 7/24/2021 11:53 AM