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[];
}
Angular Interview Q & A series Two-way binding was a functionality in Angular JS, but has been removed from Angular 2. x onwards. But now, since the event of classes in Angular 2, we can bind to properties in AngularJS class. Suppose if you had a class with a class name, a property which had a type and value.
Angular v2+ supports two-way data binding using ngModel directive and also by having getter and setter methods.
Angular's two-way binding syntax is a combination of square brackets and parentheses, [()] . The [()] syntax combines the brackets of property binding, [] , with the parentheses of event binding, () , as follows.
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));
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With