I have a component where I select a set of image objects. I want to pass these selected images to my new route, CreateAlbum. The data it nested and wouldn't be suitable to pass as URL parameters.
Is there any easy way to achieve this?
Here's my code to navigate to the route
public gotoCreateAlbum(): void {
this.router.navigate([('/create-album')])
}
My selected data sits in this variable
@Input() selectedPhotos: IPhoto[];
and this is my routing module
const routes: Routes = [
{ path: 'photos', component: PhotosComponent},
{ path: 'photos/:filter', component: PhotosComponent},
{ path: 'create-album', component: CreateAlbumComponent}
];
Basically I want to perform the same operations as if the CreateAlbum component was a child to my current component in which case I would have used @Input()
The suggested way for those interactions is via bindings (Input/Output). However, if the data does not belong to the parent component, a service is probably the better way. It is more clear and keeps the data hierarchy concise. For components that are not close in the hierarchy, a service is probably the only way.
I hope this will work. Try using Query Parameters.
<nav>
<a [routerLink]="['/component1']">No param</a>
<a [routerLink]="['/component2']" [queryParams]="{ page: 99 }">Go to Page 99</a>
</nav>
or
opencomponent2(pageNum) {
this.router.navigate(['/component2'], { queryParams: { page: pageNum } });
}
In child component :
constructor(
private route: ActivatedRoute,
private router: Router) {}
ngOnInit() {
this.sub = this.route
.queryParams
.subscribe(params => {
// Defaults to 0 if no query param provided.
this.page = +params['page'] || 0;
});
}
I have studied this on rangle.io website. Try this if it works for you. otherwise https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service is only option.
See https://angular.io/guide/router for an in-depth example. Scroll down to this code snippet:
gotoHeroes(hero: Hero) {
let heroId = hero ? hero.id : null;
// Pass along the hero id if available
// so that the HeroList component can select that hero.
// Include a junk 'foo' property for fun.
this.router.navigate(['/heroes', { id: heroId, foo: 'foo' }]);
}
To get the value of 'id' in the target component:
ngOnInit() {
this.heroes$ = this.route.paramMap.pipe(
switchMap((params: ParamMap) => {
// (+) before `params.get()` turns the string into a number
this.selectedId = +params.get('id');
return this.service.getHeroes();
})
);
}
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