Samir Boulos
Samir Boulos

Reputation: 441

Generic error when rendering an Angular component

I have a simple component but for some reason I am getting the following runtime error:

An unhandled exception occurred while processing the request.

Exception: Call to Node module failed with error: Error: Uncaught (in promise): TypeError: Cannot read property 'Name' of undefined TypeError: Cannot read property 'Name' of undefined at CompiledTemplate.proxyViewClass.View_ProductDetailsComponent0.detectChangesInternal (/AppModule/ProductDetailsComponent/component.ngfactory.js:106:69)

Below is the view:

<h2>{{product.Name}}</h2>

<strong>Price: {{product.Price | currency}}</strong>

<div style="background-color:aliceblue;border:hidden;border-radius:15px;">
    <h4>Add to Cart</h4>
    <form name="myForm">
        Quantity: <input type="number" [(ngModel)]="quantity" placeholder="quantity" name="quantity"/>
        <input type="button" (click)="AddToCart()" ng-disabled="myForm.$invalid" value="Add" class="btn btn-default" />
    </form>
</div>

Upvotes: 0

Views: 250

Answers (1)

eko
eko

Reputation: 40647

If your product field inside the component is undefined, this is likely to happen. In order to prevent this, you can either use the safe navigation operator ( it will basically do a truthy check):

{{product?.Name}}

or do an if check in the template:

<div *ngIf="product">
  {{product.Name}}
</div>

Upvotes: 1

Related Questions