This repo is following Angular Getting started to learn the basic of Angular and its best practices. Addionally, I made some modification and enhancement to the replica project to put what I’ve learned into practice. Feel free to view and edit on StackBlitz ⚡️.
- Add
isEmptyCartmethod inCartServiceto able to check if current cart is empty - Add
getTotalPricemethod inCartServiceto display total of orders - Add
getCartCountandsetCartCountinCartServiceto display cart count in top bar - Conditional template rendering in
Carttemplate based onisEmptyCart - CSS update
- Add breadcrumb based on this post written by Zhiyue Yi. I made some additional updates on this part:
- A
DynamicBreadcrumbServiceis added to declaratively specify the breadcrumb label by injecting this service - Unsubscribe subscriptios in
ngOnDestroyhook to avoid memory leak issue (credit to Kristiqn Tachev’s comment)
- A
Let’s use the example from Angular Getting started example. Next, create a breadcrumb like Products > Phone XL when we in specified product detail page. Notice that the latter part Phone XL actually comes from {{productName}} defines in angular routers. We can go back to products page when Products is clicked.
- Structure angular routes and add corresponding
breadcrumbproperties in the routes’sdata. In this case, addbreadcrumb: 'Products'to path/products, andbreadcrumb: '{{productName}}'to path/products/:productId.
const routes: Routes = [
// other routes ...
{
path: 'products',
data: {
breadcrumb: 'Products',
},
children: [
{
path: '',
component: ProductListComponent,
},
{
path: ':productId',
component: ProductDetailsComponent,
data: {
breadcrumb: '{{productName}}',
}
}
]
}
]
- Inject
DynamicBreadcrumbServiceservice in the component you want. In this case, we inject the service intoProductDetailsComponent
@Component({
selector: 'app-product-details',
templateUrl: './product-details.component.html',
styleUrls: ['./product-details.component.css'],
})
export class ProductDetailsComponent implements OnInit {
product?: Product;
constructor(
private route: ActivatedRoute,
private dynamicBreadcrumbService: DynamicBreadcrumbService
) { }
}
- Set the value
productNameusingDynamicBreadcrumbService
export class ProductDetailsComponent implements OnInit {
product?: Product;
constructor(
// other service ...
private dynamicBreadcrumbService: DynamicBreadcrumbService
) { }
ngOnInit(): void {
// other code ...
// Update breadcrum dynamically
const breadcrumbLabel = { productName: this.product?.name };
this.dynamicBreadcrumbService.updateBreadCrumbLabels(breadcrumbLabel);
}
}
Leave a Reply