如何将一个组件导航到另一个组件

时间:2017-12-30 13:08:11

标签: angular2-routing

我在这里使用angular2这里我在EditEmployeeByIdComponent中注册EmployeeModule当用户点击该网址时,它会将我重定向到该Componet

EditEmployeeByIdComponent

import { Component } from "@angular/core"
@Component({
    templateUrl:'../../ui/employee/EditEmployee.html'
})
export class EditEmployeeByIdComponent {
}

我在EmployeeModule中注册了EditEmployeeByIdComponent

@NgModule({
    imports: [RouterModule.forChild(EmployeeRoute), FormsModule, CommonModule, HttpModule],
    declarations: [EmployeeComponent, EditEmployeeByIdComponent],
    bootstrap: [EmployeeComponent],
    providers: [EmployeeService]
})

export class EmployeeModule {
}

从这个Im呼唤

<tr *ngFor="let emp of employee">
    <a (click)="GetById(emp.Emp_Id)"> {{emp.EmpName}} </a>
</tr>


 GetById(Id:number) {
    this._router.navigate(['../editemployeebyidcomponent'], {})            
}

1 个答案:

答案 0 :(得分:0)

你必须在你的父组件中提供路由器插座,所以允许angular在其上呈现子节点,所以在你的例子中你必须声明一个父组件让我们说Employee.component.ts和它的等效模板Employee.component .html和里面.html写这个指令不要忘记在你的 EmployeeModule

中声明这个父母
const  employeeRoutes: Routes = [
  {path : 'employee', component: EmployeeComponent,children: [
    {path : 'editemployeebyidcomponent', component: EditEmployeeByIdComponent},
    ];

@NgModule({
  imports: [
    CommonModule,
    RouterModule.forChild(employeeRoutes)
  ],
  declarations: [
    EmployeeComponent,EditEmployeeByIdComponent
  ],
  exports :[RouterModule]
})
export class EmployeeModule { }

<强> employee.component.html

<router-outlet></router-outlet>

<强> app.module.ts

const  appRouts: Routes = [
  {path: 'employee' , component: EmployeeComponent}
];

@NgModule({
  imports: [ 
    BrowserModule,
    RouterModule.forRoot(appRouts),
  ],
  declarations: [ App ],
  bootstrap: [ App ]
})
export class AppModule {}

您在父组件中的导航路径应该是那样的

 GetById(Id:number) {
        this._router.navigate(['../editemployeebyidcomponent'],{relativeTo: this.currentActivatedRoute})

}

要么使路线绝对

 GetById(Id:number) {
        this._router.navigate(['/editemployeebyidcomponent'])

}