Null guarding in Angular
In JavaScript, the undefined and null values are a persistent issue that must be proactively dealt with every step of the way. This is especially critical when dealing with external APIs and other libraries. If we don't deal with undefined and null values, then your app may present badly rendered views, console errors, issues with business logic, or even a crash of your entire app.
There are multiple strategies to guard against null values in Angular:
- Property initialization
- The safe navigation operator,
?. - Null guarding with
*ngIf
You may use one or more of these strategies. However, in the next few sections I demonstrate why the *ngIf strategy is the optimal one to use.
To simulate the scenario of getting an empty response from the server, go ahead and comment out the getCurrentWeather call in ngOnInit of CurrentWeatherComponent:
src/app/current-weather/current-weather.component.ts
ngOnInit(): void...