Freddy Freddy - 3 months ago 25
AngularJS Question

Angular2 NgRouter with shared parent component

I have the following components in my angular 2 typescript application:


  • AppComponent

  • ProjectComponent


    • ProjectListComponent

    • ProjectNewComponent




I have a simple layout, which should be the same on all pages, so I put the following html code for the main component:

<h1>Welcome</h1><a routerLink="/">Home</a>
<hr />
<router-outlet></router-outlet>


As far as I understand, the router injects its content in the
<router-outlet>
. Now I wanted to create a nested project component. For simplicity, the project component should consist of three parts. One parent component, which only holds the headline and a container and two child components which are nested in the parent component.

My
app.routing.ts
looks as follows:

const appRoutes : Routes = [
{
path: 'project',
component: ProjectComponent,
children: [
{ path: 'id/:id', component: ProjectEditComponent },
{ path: 'new', component: ProjectNewComponent }
]
}
];


My question is: How must the
Project
component and the
ProjectList
component look like?

So far I have
project.html
:

<h3>Projects</h3>
<hr />
<project-list></project-list>
<project-new></project-new>


My goal is something like, whenever I call
ProjectListComponent
or
ProjectNewComponent
:

<h3>Projects</h3>
<hr />
<div>
<project-current-component></project-current-component>
</div>


How can I achieve that? The advantage of this would be that I don't have to rewrite any html code.

Answer

If i correctly understand what you want are trying to achieve, your Projects component should also include a router outlet (in angular2 RC5 that i am working with lately, nesting router outlets is allowed).

AppComponent would be something like:

<h1>This is the app component title</h1>
<router-outlet></router-outlet>

ProjectComponent would be :

<h3>Projects</h3>
<router-outlet></router-outlet>

And the child components of ProjectsComponent would be :

<h5>Child components area</h5> 
<div>
<!-- place whatever code you have inside here -->   
     <project-current-component></project-current-component>
</dir>