There is a scenario where we have an object defined by an interface, with the option for both category
and its nested name
:
export interface Product {
category?: {
name?: string,
}
}
The objective now is to display an element only if both the category
and its name
are present:
<h1 *ngIf="product.category?.name">{{ product.category.name }}</h1>
However, this code snippet results in an error:
TS2532: Object is possibly 'undefined'.
<h1 *ngIf="product.category?.name">{{ product.category.name }}</h1>`<br>
~~~~
There are alternative solutions to address this issue:
<h1 *ngIf="product.category?.name">{{ product.category?.name }}</h1>
<h1 *ngIf="product.category && product.category.name">{{ product.category.name }}</h1>
This raises the question: Why does the initial solution fail to work as expected?