代码之家  ›  专栏  ›  技术社区  ›  Sabith

角2子布线不工作

  •  0
  • Sabith  · 技术社区  · 6 年前

    我正在尝试在应用程序中实现子路由器。 我所做的是,单击侧菜单,我将以

    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>
    
    2 回复  |  直到 6 年前
        1
  •  1
  •   Jack M    6 年前

    这通常是由于 <router-outlet> 是。它应该是应用程序中唯一可更改的部分 如果它不在主要部件中,请检查其位置

        2
  •  0
  •   kzrfaisal    6 年前

    试试这个

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

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

    import { ActivatedRoute } from '@angular/router';
    
    constructor(private route: ActivatedRoute)