我现在有以下模板
<project-form [nextId]="projects.length" (newProject)="addProject($event)"></project-form> <project-list [projects]="projects"></project-list>
在ProjectAppComponent中.
class ProjectAppComponent { projects: Project[] = [ { id: 0,title: "Build the issue tracker" },{ id: 1,title: "Basecamp" },] addProject(project: Project) { this.projects.push(project); } }
ProjectAppComponent具有项目数组和将新项目推入其中的方法.我想为项目表单和项目列表创建子路由,这样我就可以执行/ projects / new和/ projects / show来显示表单或列表.我创建了这样的路线配置 –
@Component({ template: ` <div> <router-outlet></router-outlet> </div> `,directives: [ RouterOutlet ] }) @RouteConfig([ { path: '/list',name: 'ProjectList',component: ProjectListComponent,useAsDefault: true },{ path: '/new',name: 'ProjectForm',component: ProjectFormComponent },]) class ProjectAppComponent { projects: Project[] = [ { id: 0,] addProject(project: Project) { this.projects.push(project); } }
对于ProjectAppComponent类本身.现在的问题是我不知道如何将项目数组(模板中的[projects] =“projects”)传递给ProjectListComponent,因为< project-list>选择器不再使用(必须使用< router-outlet>). ProjectListComponent依赖于@Input()项目:Project来渲染所有项目.我该如何解决这个问题?这是项目列表组件 –
@Component({ selector: 'project-list',template: ` <ul> <project-component *ngFor="#project of projects" [project]="project"></project-component> </ul> `,directives: [ProjectComponent] }) class ProjectListComponent { @Input() projects: Project[]; }
解决方法
你不能只使用一项服务吗?
import {Injectable} from 'angular2/core'; import {Project} from '...'; @Injectable() export class ProjectService { public projects: Project[] = [ { id: 0,]; addProject(...args): number { return this.projects.push(new Project(...args)); } }