【问题标题】:Angular 2 sub routing not workingAngular 2子路由不起作用
【发布时间】:2018-06-25 09:55:48
【问题描述】:

我正在尝试在我的应用程序中实现子路由器。 我所做的是,点击侧边菜单,我将导航到孩子

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

但它没有执行子组件,而是再次执行父组件。

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}
 ];

父组件

 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']);
    }
 }

子组件:

 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(){}
}

发生的事情是,它导航到父级并且工作正常。当我单击左侧菜单时,我可以看到 url 变化几秒钟,然后重新加载父级,从 url 中删除子名。我该如何解决?我在实施过程中遗漏了什么?

父模板

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

【问题讨论】:

标签: angular angular2-routing


【解决方案1】:

这通常是由您的&lt;router-outlet&gt; 所在位置引起的。它应该是您的应用程序中唯一变化的部分 如果不在主组件中,则检查位于何处

【讨论】:

  • 我编辑了我的回复,很抱歉没有渲染路由器插座。你也可以分享你的父组件
  • 已编辑。现在添加父组件
【解决方案2】:

试试这个

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

这里的this.route是ActivatedRoute的一个实例。

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

constructor(private route: ActivatedRoute)

【讨论】:

    猜你喜欢
    • 2017-03-03
    • 1970-01-01
    • 1970-01-01
    • 2017-05-05
    • 2016-09-20
    • 1970-01-01
    • 2017-12-12
    • 2019-02-01
    • 1970-01-01
    相关资源
    最近更新 更多