8
votes

I've the following template at the moment

<project-form [nextId]="projects.length" (newProject)="addProject($event)"></project-form>
<project-list [projects]="projects"></project-list>

inside the ProjectAppComponent.

class ProjectAppComponent {
    projects: Project[] = [
        { id: 0, title: "Build the issue tracker" },
        { id: 1, title: "Basecamp" },
    ]

    addProject(project: Project) {
        this.projects.push(project);
    } 
}

The ProjectAppComponent has the projects array and the method that pushes new items into it. I want to create child routes for project form and project list so I can do /projects/new and /projects/show to show either the form or the list. I created the routes configurations like this -

@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, title: "Build the issue tracker" },
        { id: 1, title: "Basecamp" },
    ]

    addProject(project: Project) {
        this.projects.push(project);
    } 
}

for the ProjectAppComponent class itself. The problem now is that I don't know how I would pass the projects array ([projects]="projects" in the template) to the ProjectListComponent since the <project-list> selector is not longer used (have to use <router-outlet>). ProjectListComponent depends on the @Input() project: Project to render all the projects. How should I go about resolving this issue? Here's the project list component -

@Component({
    selector: 'project-list',
    template: `
        <ul>
            <project-component *ngFor="#project of projects" [project]="project"></project-component>
        </ul>
    `,
    directives: [ProjectComponent]
})
class ProjectListComponent {
    @Input() projects: Project[];
}
1

1 Answers

6
votes

Couldn't you just use a service?

import {Injectable} from 'angular2/core';
import {Project} from '...';


@Injectable()
export class ProjectService {
  public projects: Project[] = [
    { id: 0, title: "Build the issue tracker" },
    { id: 1, title: "Basecamp" },
  ];

  addProject(...args): number {
    return this.projects.push(new Project(...args));
  }
}