When it comes to routing in Angular, I have been following the Angular tutorial from documentation. My example application integrates Angular components with an ASP.NET Core 2.2 web app, and these components are displayed within .cshtml views.
I use Angular component selectors in my ASP.NET Core views, like in the index.cshtml file where all Angular views are rendered:
Index View
<current-time></current-time>
<app-top-bar></app-top-bar>
<app-product-list></app-product-list>
Everything was being displayed correctly until I tried to add routing to the ProductListComponent
in the product-list.component.html:
<h2>Products</h2>
<div *ngFor="let product of products">
<h3>
<a [title]="product.name + ' details'" [routerLink]="['/products', product.productId]">
{{ product.name }}
</a>
</h3>
<p *ngIf="product.description">
Description: {{ product.description }}
</p>
<button (click)="share()">
Share
</button>
<app-product-alerts [product]="product"
(notify)="onNotify()">
</app-product-alerts>
</div>
The issue arises when hovering over product
in the product-list view as instead of receiving the anchor path
http://localhost:59119/products/1
, I get http://localhost:59119/products/undefined
.
Additionally, navigating to
http://localhost:59119/products/1
results in a 404
error. It seems like there might be a problem related to not having bootstrap: [ AppComponent]
defined in the app.module.ts.
Despite displaying Angular views using .cshtml files, is there a way to fix the navigation to the product details?
product-details.component.ts:
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { products } from '../products';
@Component({
selector: 'app-product-details',
templateUrl: './product-details.component.html',
styleUrls: ['./product-details.component.css']
})
export class ProductDetailsComponent implements OnInit {
product;
constructor(
private route: ActivatedRoute,
) { }
ngOnInit() {
this.route.paramMap.subscribe(params => {
this.product = products[+params.get('productId')];
});
}
}
products.ts:
export const products = [
{
productId: 1,
name: 'Phone XL',
price: 799,
description: 'A large phone with one of the best screens'
},
{
productId: 2,
name: 'Phone Mini',
price: 699,
description: 'A great phone with one of the best cameras'
},
{
productId: 3,
name: 'Phone Standard',
price: 299,
description: ''
}
];
product-list.component.ts:
import { Component, OnInit } from '@angular/core';
import { products } from '../products';
@Component({
selector: 'app-product-list',
templateUrl: './product-list.component.html',
styleUrls: ['./product-list.component.css']
})
export class ProductListComponent implements OnInit {
products = products;
share() {
window.alert('The product has been shared!');
}
onNotify() {
window.alert('You will be notified when the product goes on sale');
}
constructor() { }
ngOnInit() {
}
}