Monday, March 19, 2018

how to navigate from component to another component



Here I have got two components named, Main.cmp and C1.cmp. You can navigate from Main.cmp to C1.cmp using the below snippets.


Main.cmp
1<aura:component implements="force:appHostable,flexipage:availableForAllPageTypes">
2     
3    <ui:button label="Navigate to C1" press="{!c.Navigate}"/>
4     
5    {!v.body}
6     
7</aura:component>

MainController.js
01({
02    Navigate : function(component, event, helper) {
03         $A.createComponent(
04            "c:C1",
05            {
06                  
07            },
08            function(newCmp){
09                if (component.isValid()) {
10                    var body = component.get("v.body");
11                    body.push(newCmp);
12                    component.set("v.body", body);
13                }
14            }
15        );         
16         
17    }
18})


C1.cmp
1<aura:component >
2     
3    Component C1 Successfully Loaded ! ! !
4     
5</aura:component>

---------------------------------------------------------------------------------------------------------------
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>