Home > Software engineering >  Object is possibly null in HTML - Angular 13
Object is possibly null in HTML - Angular 13

Time:06-24

i am using latest version of angular and in one html file i am getting Object is possibly null when accessing a child property

for instance, *ngFor="let child of parent.children"

it is complaining that children is possibly null.

its not just arrays either. in another spot it is complaining parent.parent is possibly null

the weird thing is its only happening in one file. which leaves me to believe there is a problem with the file but its not telling me. its giving me these wierd errors instead

i am able to compile and run the app because i added "strictNullChecks": false to the tsconfig.json file. i can navigate to this page and it displays w/o error and everything on it works perfectly fine but it annoys me that visual studio code marks the file red as if there is an error.

does anyone have any ideas why this is happening?

CodePudding user response:

this happens because the object is possibly null in your definition / assignment of the property. Can't say specifically why without seeing how the property is defined and assigned, but simplest / fairly universal fix is to use null safe operator:

*ngFor="let child of parent?.children"

CodePudding user response:

i was initializing parent to null....

parent: IParent | null;

....once i removed | null... the errors went away

  • Related