0

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?

2 Answers 2

1

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"
Sign up to request clarification or add additional context in comments.

1 Comment

thank you for the quick response. i tried that already and no luck still complaining.. but your answer got me looking and helped me to figure it out. i was initializing it to null.... parent: IParent | null; ....once i removed | null... the errors went away ! thank you so much
0

I was initializing parent to null...

parent: IParent | null; 

Once I removed | null the errors went away.

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.