Reputation: 14404
I'm devolping a web application using Angular v2.0.0
. Since I have a sub-navigation in my app I would like to pass some data to a sub-page, that loads its own component, through the <router-outlet>
.
As i can see on Angular2 documentation I can reach this purpose if i include a sub-page directive in the main component template, but this isn't what i need.
I'd like to use code like the following:
app.routes.ts
export const routes: RouterConfig = [
{ path: '/', redirectTo: '/one' },
{ path: '/one', as: 'One', component: OneComponent },
{ path: '/two', as: 'Two', component: TwoComponent },
{ path: '/three', as: 'Three', component: ThreeComponent }
];
export const APP_ROUTER_PROVIDERS = [
provideRouter(routes)
];
main.component.ts
@Component({
moduleId: module.id,
selector: 'main',
templateUrl: 'main.component.html'
})
export class MainComponent {
maindata: Object = {name:'jim'};
}
main.component.html
<h1>Home</h1>
<a [router-link]="['./sub1']">One</a> |
<a [router-link]="['./sub2']">Two</a> |
<a [router-link]="['./sub3']">Three</a>
<hr/>
<router-outlet [data]="maindata"></router-outlet>
one.component.ts
@Component({
moduleId: module.id,
selector: 'one',
inputs: ['data'],
templateUrl: 'one.html'
})
export class OneComponent {
@Input() data;
}
one.component.html
<h2>{{ data.name }}</h2>
...
How to do this?
Upvotes: 1
Views: 220
Reputation: 8959
You can pass data directly into a component through the route using resolvers. First step is to register the resolver:
@NgModule({
...
providers: [
ExampleService,
{
provide: 'foo',
useValue: () => {
return {
msg: 'Something something something'
};
}
]
})
export class AppModule {}
Then make use of it in the routes:
export const AppRoutes: Routes = [
...
{
path: '/one',
component: OneComponent,
resolve: {
foo: 'foo'
}
}
];
The final thing to do is to make use of it in the component:
@Component()
export class OneComponent implements OnInit {
foo;
constructor(private route: ActivatedRoute) {}
ngOnInit() {
this.foo = this.route.snapshot.data['foo'];
}
}
See this ThoughtRam post for more
Upvotes: 1
Reputation: 290
You can pass argument, for example argument id for 'user' link would be written as 'user/:id' and you can take this argument later. Also, you can use @Input() and @Output() annotations
Upvotes: 0