0

I have this in my angular html file where the each of the fields (i.e. product.name) gives me an Object is possibly 'undefined' error.

How do I change the lines to handle this?

This is from a tutorial I am doing where this is the exact code and it doesn't mention the errors, so I don't know how to fix this.

I am using this in StackBlitz and I don't have a tsconfig.js file where I can change a setting to fix it.

Thanks,

Tom

tshad
  • 335
  • 2
  • 4
  • 18
  • 1
    Does this answer your question? [How can I solve the error 'TS2532: Object is possibly 'undefined'?](https://stackoverflow.com/questions/54884488/how-can-i-solve-the-error-ts2532-object-is-possibly-undefined) – Yong Shun Aug 16 '21 at 07:19

1 Answers1

3

This is probably happening due to strict type checking. Please use product?.name instead (and use ? for the rest of the properties that you access on the product object) to make the compiler happy. You can even use ! (not null assertion operator) because you already check using ngIf and you are sure that the object has a value.

Octavian Mărculescu
  • 4,312
  • 1
  • 16
  • 29
  • Putting the ? after each product (product?.name), worked. But I am confused. This comes from the angular.io tutorials and they didn't have the question mark (I copied and pasted the code). Another tutorial had the same thing and using the strictNullChecks solved the issue but the tutorial doesn't mention it and I am using there project with Stackblitz. Am I missing something? Also, it only worked when I removed the "| currency". I was getting another error: "No pipe found with name 'currency'." – tshad Aug 16 '21 at 16:52
  • The `currency` pipe should work if you import `CommonModule`. Check this out https://angular.io/api/common/CurrencyPipe – Octavian Mărculescu Aug 16 '21 at 19:28