Data binding with angular 2 route components

I have the following template at the moment

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

inside ProjectAppComponent.

 class ProjectAppComponent { projects: Project[] = [ { id: 0, title: "Build the issue tracker" }, { id: 1, title: "Basecamp" }, ] addProject(project: Project) { this.projects.push(project); } } 

ProjectAppComponent has an array of projects and a method that pushes new elements towards it. I want to create child routes for the project form and project list so that I can do /projects/new and /projects/show to show either the form or the list. I created route 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 is that I don’t know how to pass an array of projects ( [projects]="projects" in the template) to ProjectListComponent, since the <project-list> selector is no longer used (I need to use <router-outlet> ). ProjectListComponent depends on @Input() project: Project to display all projects. How do I solve this problem? Here the project list component is

 @Component({ selector: 'project-list', template: ` <ul> <project-component *ngFor="#project of projects" [project]="project"></project-component> </ul> `, directives: [ProjectComponent] }) class ProjectListComponent { @Input() projects: Project[]; } 
+7
javascript angularjs angular angular2-routing
source share
1 answer

Could you just use the 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)); } } 
+5
source share

All Articles