prabhu
prabhu

Reputation: 369

How to prevent the UI from crashing in angular 4

I have an angular 4 app. The HTML page on of my component is <p> {{ myJson['Key'].toLowerCase() }} </p>. But, the problem is sometimes 'Key' would not be present in some JSON files and the UI crashes with

TypeError: Cannot read property 'toLowerCase' of undefined

I have an error handler class myErrorHandler extends ErrorHandler that logs all the errors. But, sometimes due to invalid json data, the key may be absent or the data might not be there. apart from using *ngIf to check each and every tag, is there a way i could prevent the UI from crashing? When the crash happenes, The UI elements are not aligned properly (imagine one element is kind of laid besides a replica of itself). If i want to prevent this from happening, what are the ways?

Thanks in advance. Any help is greatly appreciated.

Upvotes: 0

Views: 677

Answers (1)

Dai
Dai

Reputation: 155493

Use the "Elvis operator" ?. (aka the "Safe Navigation" operator):

<p>{{ myJson?.Key?.toLowercase() }}</p>

Upvotes: 3

Related Questions