When my Angular component HTML renders. I will get lots of errors that look like this
ERROR TypeError: Cannot read properties of undefined (reading ‘someProperty’)
In my HTML page, I have lots of bindings that look like this
<h1>{{event.title.toUpperCase()}}</h1>
In most components I call a service to fetch data from my controller in the ‘ngOnInit()’ and I know that one solution to prevent this error before the data comes back from my controller is to make the property nullable like this
event?.title
but this doesn’t seem like a practical solution, especially if I have dozens on the page.
What I have tried –
- Making them nullable with a ‘?’ but that doesn’t seem correct, especially if I always doing it
- Setting the object type being returning from the controller to a ‘any’ (ex. event: any), but in some cases it still shows an error
QUESTION – What’s the best solution to handle this so I don’t keep getting these errors until my page data loads?
Should I have some conditional like *ngIf=”event” and hide the page until the data is received and show some loading indicator while waiting? Or is some way to jsut prevent these error from showing in the console?