如何在Angular 2中正确配置高级路由

时间:2016-02-05 08:46:17

标签: angular angular2-routing angular2-forms

我是棱角分明的新人。我有一个包含表单步骤的项目创建页面。 第一步创建项目,然后在其他步骤中我只更新每个步骤的相关信息。正如我想象的那样,路线应该是这样的:

project/form              // for creating new project
project/form/:id          // for updating a project
project/form/:id/step2    // for updating second step
projectform/:id/step3     // .........

所有以前的路由共享相同的主要组件。我的组件如下所示,主要组件加载到routerOutlet中,里面有步骤组件:

enter image description here

这条路线:

@RouteConfig([
    {path: '/project/form', name: 'Project_Form', component: ProjectFormComponent, useAsDefault: false},
    //new AuxRoute({path: '/:id', component: ProjectFormComponent}),
])

我可以指定我应该从路线显示哪个步骤,或者我必须将步骤名称设置为主要组件中它们之间切换的参数。对于这种情况的任何建议,我是否正确做到了?

1 个答案:

答案 0 :(得分:3)

您可以将步骤作为附加参数传递。

@RouteConfig([
    {path: '/project/form', name: 'Project_Form', component: ProjectFormComponent, useAsDefault: true},
    {path: '/project/form/:id', name: 'Project_Form', component: ProjectFormComponent},
    {path: '/project/form/:id/:step', name: 'Project_Form', component: ProjectFormComponent},
])

您的ProjectFormComponent应该是这样的

import {RouteParams} from "angular2/router";

@Component({
   ...
   template: `
   <step-1 *ngIf='step == 1'></step-1>
   <step-2 *ngIf='step == 2'></step-2>
   <step-2 *ngIf='step == 2'></step-2>
   `
})
export class ProjectFormComponent {

    constructor(params: RouteParams, public step){
       if(params.get('id'){
           if(params.get('step')){ 
              this.step = parseInt(params.get('step'))
              editProject(params.get('id'), this.step)
           } else() { 
              this.step = 1 
              editProject(params.get('id'), 1)
           } 
       } else {
           this.step = 1
           createNewProject()
       }
    }
    createNewProject(){
       ...
    }
    editProject(id, step) { 
       ... 
    }
}

step在模板中可用,以选择性地显示所需的部分