Sabith
Sabith

Reputation: 1656

Angular 2 sub routing not working

I am trying to implement child router in my application. what I did is, on click of side menu , I am navigating to the child as

this._router.navigate(['/parent/child']);

but its not executing the child component, instead parent component is getting executed again.

router in app.module.ts

const appRoutes: Routes = [
   { path: 'login', component: LoginComponent },
   {path:'parent',
       children:[
           {path: '', component: ParentComponent, pathMatch: 'full'}
          ,{path:"child",component:ChildComponent,
             outlet:'content'
           }]
   },
   {path:'**',component:LoginComponent}
 ];

ParentComponent

 import { Component } from '@angular/core';
 import {Router} from '@angular/router';
 import {OnInit} from '@angular/core';

 @Component({
   selector: 'login',
   templateUrl: 'app/parent.template.html'
 })
 export class ParentComponent  implements OnInit{  
  constructor(private _router: Router){} 
   ngOnInit(){}
   menuClicked(event:any):void{             
        let elements = event.target.parentElement.children;
        for(let i=0;i<elements.length;i++){
            elements[i].classList.remove('active')
        }
        event.target.classList.add('active');
        this._router.navigate(['/parent/child']);
    }
 }

ChildCOmponent:

 import { Component } from '@angular/core';
 import {Router} from '@angular/router';
 import {OnInit} from '@angular/core';

 @Component({
    templateUrl: 'app/child.template.html',
 })
 export class IncidentComponent  implements OnInit{  
    constructor(private _router: Router){} 
    ngOnInit(){}
}

What happened is, it navigated to parent and its working fine. When i click left menu, i can see the url change for a fraction of seconds and then its reloading the parent, removing the child name from the url. How can i fix it? What I missed in the implementation?

Parent Template

<div class="home-container row">
   <div class="home-body col-12">
       <div class="home-header row">

       </div>
       <div class="home-contents row">
          <div class="left-menu col-2">
          </div>
       <div class="right-contents col-10">
          <router-outlet name="content"></router-outlet>
       </div>
   </div>
 </div>

Upvotes: 1

Views: 516

Answers (2)

kzrfaisal
kzrfaisal

Reputation: 1443

Try this

this._router.navigate(['child'],{relativeTo: this.route});

Here this.route is an instance of ActivatedRoute.

import { ActivatedRoute } from '@angular/router';

constructor(private route: ActivatedRoute)

Upvotes: 0

Jack M
Jack M

Reputation: 2574

This is often caused by where your <router-outlet> is. It is supposed to be the only changing part of your application Check where is located if it is not located in the main component

Upvotes: 2

Related Questions