Reputation: 391
Hi I am new to angular 4 and I am creating a shop page where when a user clicks the jeans link it should visit the shop page with the filtered jeans products. (Please let me know if you need more info about the code, I can add it.)
In Home Component -
<a [routerLink]="['/shop']">Jeans</a>
<a [routerLink]="['/shop']">Shirts</a>
I have created a shop component and given route as /shop
. In my shop component I have created the service which fetches the data from -
import { Products } from './products';
export const PRODUCTS: Products[] = [
{
id: 1,
productCat:'Jeans',
product: [
{
prodId: 1a;
productName: 'Trendy Jeans',
},
],
},
{
id: 2,
productCat:'Shirts',
product: [
{
prodId: 1b;
productName: 'Trendy Shirts',
},
],
}
]
So, is it possible to use query params
or optional params
in angular routing to fetch only jeans data in shop page after clcking the link jeans or shirts data after clicking the link shirts. If its not possible can you please suggest me a different method.
Upvotes: 0
Views: 1369
Reputation: 1292
Yes, query params are available in angular. Your link might look something like this:
<a [routerLink]="['/shop']" [queryParams]="{type: 'jeans'}">Jeans</a>
<a [routerLink]="['/shop']" [queryParams]="{type: 'shirt'}">Shirts</a>
Accessing queryParams in your shop component would look something like this:
this.activatedRoute.queryParams
.flatMap(queryParams => {
if (queryParams.type === 'shirt') {
// get shirt
} else if(queryParams.type === 'jeans') {
// get jeans
}
})
Upvotes: 1
Reputation: 6983
In your routes file.
{ path: 'shop/:data, component: ShopComponent }
Then in your products componet where you have links to the shop component, Pass the parameters you want.
import { Router } from '@angular/router';
your component code goes here. And for the link click function add this.
this.router.navigate(['/project-details',data]);
data in here is for your extracted data.
And in your product component constructor or ngOnInit sunscribe for the route params.
ngOnInit() {
this.sub = this.route.params.subscribe((params) => {
const data: params.data;
});
}
Hope this helps. And if you need to find more about angular routing and navigation follow this link.
Upvotes: 1