Reputation: 81
I'm following the View Product Details tutorial on the angular website and encountered the error:
Error in src/app/product-details/product-details.component.html (4:16) Object is possibly 'undefined'.
I can't proceed to the next tutorial because it needs this page to function.
Here is the code:
product-list.component.html
<h2>Products</h2>
<div *ngFor="let product of products">
<h3>
<a [title]="product.name + ' details'" [routerLink]="['/products', product.id]">
{{ product.name }}
</a>
</h3>
</div>
product-details.component.ts
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Product, products } from '../products';
@Component({
selector: 'app-product-details',
templateUrl: './product-details.component.html',
styleUrls: ['./product-details.component.css']
})
export class ProductDetailsComponent implements OnInit {
product: Product|undefined;
constructor(
private route: ActivatedRoute,
) { }
ngOnInit() {
// First get the product id from the current route.
const routeParams = this.route.snapshot.paramMap;
const productIdFromRoute = Number(routeParams.get('productId'));
// Find the product that correspond with the id provided in route.
this.product = products.find(product => product.id === productIdFromRoute);
}
}
product-details.component.html
<h2>Product Details</h2>
<div *ngIf="product">
<h3>{{ product.name }}</h3>
<h4>{{ product.price | currency }}</h4>
<p>{{ product.description }}</p>
</div>
I hope someone can help to figure out the problem because I see the code is functioning.
Thank you.
Upvotes: 3
Views: 1482
Reputation: 81
tsconfig.json file
"strict": false,
Turn off the strict. Angular will able to compile successfully.
Upvotes: 0
Reputation: 1
I fixed that by adding 'ProductDetailsComponent' import in 'app.module.ts'
Upvotes: 0
Reputation: 91
I'm also doing this tutorial and I fixed it by adding the ProductDetailsComponent to the declarations inside app.module.ts.
declarations: [
AppComponent,
TopBarComponent,
ProductListComponent,
ProductAlertsComponent,
ProductDetailsComponent //<-- add this into declarations
],
Don't forget to import first the ProductDetailsComponent in app.module.ts.
import { ProductDetailsComponent } from './product-details/product-details.component';
It should work after refreshing the entire website (not just the display to the right, go save and refresh the browser tab).
Upvotes: 9