Dealing with null exceptions in Angular 4: Best practices

Hi there, I am encountering an issue with binding my model data to HTML fields where when I try to edit the data it returns an error saying "cannot read value of null". How can I resolve this?

Here is the HTML code snippet:


<div class="form-group">
      <input type="text" [(ngModel)]="patient?.Address.Address1" name="address1"
             class="form-control input-underline input-lg" id="address1"
             placeholder="Address1" maxlength="50" autocomplete="off">
    </div>
    <div class="form-group">
      <input type="text" [(ngModel)]="patient?.Address.Address2" name="address2"
             class="form-control input-underline input-lg" id="address2"
             placeholder="Address 2" maxlength="50" autocomplete="off">
    </div>

<!-- More HTML code omitted for brevity -->

Below is the model:


export class Patient {
 id?: number;
 Email?: string;
 Address? = {
   Address1: '',
   Address2: '',
   City: '',
   State: '',
   Zip: '',
   County: '',
   Country: ''
   };
 }

And here is the TypeScript file snippet:


public patient: Patient;

ngOnInit() {

  this.store.select("patient").subscribe(patient => {
    this.patient = Object.assign({}, new Patient(), patient);
    if (this.patient.Id && !this.patientSnapshot) {
      this.patientSnapshot = {...this.patient};
    }
  });

 });
}

When attempting to edit the address, an error occurs stating "cannot read property address 1 of null". Is there a way to handle this error even if the value from the backend is null or an empty string? Thank you.

Answer №1

Your approach is attempting to utilize 2-way binding with an object that may not exist, and also has a property that may be missing. This method won't function properly when using [(ngModel)], but can be successful if you divide the binding like so.

<input type="text" [ngModel]="patient?.Address?.Address1" (ngModelChange)="functionToHandleSettingValue($event)" name="address1" >

By separating the data binding in this manner, you manage both inputting data with ngModel and outputting data with ngModelChange.

Additionally, remember that in the ngModel statement, it should be

[ngModel]="patient?.Address?.Address1"

including elvis operators for both patient and Address since they are both possibly nullable.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Why does my jQuery map code work in version 2.0 but not in version 3.0?

I've encountered an error with a jQuery map snippet that I'm trying to troubleshoot. It was working fine under jQuery 2, but after upgrading to version 3, it doesn't work anymore and I can't figure out why. Feeling stuck! var menuIte ...

Aligning the tooltip element vertically

I've created a unique flexbox calendar layout with CSS tooltips that appear on hover. One challenge I'm facing is vertically aligning these tooltips with the corresponding calendar dates effectively. Although I prefer to achieve this alignment u ...

The Ajax POST request encounters failure, although it functions properly in the console

The ajax function below is encountering an error message with little information, simply stating "error": var form = formInfo; var url = $(formInfo).attr("action"); var data = $(formInfo).serialize(); $.ajax({ type: "post", url: ur ...

I encounter an issue when trying to declare an enum in TypeScript

At line 26 in my typescript file, the code snippet below shows an enum definition: export enum ItemType { Case = 'Case', Study = 'Study', Project = 'Project', Item = 'Item', } I am currently using Visual Stu ...

Responsive Alignment of Slanted Edges using CSS

I have been working on creating a responsive diagonal layout with slanted shapes (refer to the image attached). However, I'm facing a challenge with aligning the edges smoothly at different screen sizes, especially when the rows grow and the screen re ...

Guide on altering the cell's background hue depending on its value through javascript

I'm dealing with a table that has 3 columns: field1 is a Category field2 and field3 contain Measures (specifically integers 1, 2, 3, 4, and 5). Is there a way to use Javascript to conditionally format the background color of cells in the table hol ...

The imported `theme` as `theme` was not visible in the file './theme'. The only possible export in the file is `default`

Encountering an error while attempting to export the theme from the index.js file. Below is the snippet of code present in the index.js file. import { createTheme } from "@mui/material"; import shadows from "./shadows"; import typograph ...

Eavesdrop on outbound requests on a web page using JavaScript

As I develop a single-page application that integrates a third-party analytics tool (such as Heap, Segment, Mixpanel, etc.), I am looking to actively monitor the outgoing HTTPS requests from my app and take necessary actions, such as logging. I am curious ...

Visualizing JSON data in React.js using Chart.js

Currently, as a beginner in ReactJS, I am working on an application that displays COVID-19 data from a JSON API in a visual format using Chart.js. However, despite trying various solutions, I am unable to visualize the data. Below is my source code: App ...

Utilizing Vue 3 to transform an item within a list by referencing its index

Storing the element's index in a global variable is causing issues when trying to individually edit each of them. Adding multiple elements with similar properties but being unable to edit them separately due to alterations affecting the rest is a chal ...

Sending a request for the second time may result in data duplication

To upload a file to the server, I use the following code snippet: var fd = new FormData(); fd.append('folder', 'html'); fd.append('permission', 0); fd.append("file", file, file.name); After selecting the file from an input f ...

Guide on updating location and reloading page in AngularJS

I have a special function: $scope.insert = function(){ var info = { 'username' : $scope.username, 'password' : $scope.password, 'full_name' : $scope.full_name } $http({ method: &ap ...

Interactive Range Slider for Scrolling Through Div Content

I am currently facing an issue where I want to implement a HTML range slider for controlling the horizontal scrolling of a div located below. This functionality is similar to that of a scroll bar, but it will be positioned away from the scrollable content ...

Azure deployment for Angular app was unsuccessful due to npm startup failure

I've been trying to deploy my Angular application on Azure. While I can successfully publish it using Azure, I keep encountering an error message when trying to access the published site: AggregateException: One or more errors occurred. (One or more ...

Attempting to update information in JSON using AJAX and PHP

I am attempting to update key values in a JSON object using PHP, AJAX, and JavaScript to display the new values. Here is an example of my JSON database that needs to be modified: "answer01count": "1", "answer02count": "2", "answer03count": " ...

What is the best way to access a cached value?

I am currently utilizing the node-cache-manager library to manage caching in my Node.js application. After successfully adding an item to the cache using the following code: import cacheManager from 'cache-manager'; const memoryCache = cacheMan ...

"The controller seems to always return an 'undefined' value for the Angular

Within my project, I have implemented ui-view with the following structure: <main class="content"> <div class="inner" ng-controller="OrderPageController"> <div ui-view="main-info"></div> <div ui-view="comment ...

Is there a way for me to automatically update a webpage every 5 minutes, beginning at 8:01 a.m., and subsequently at 8:06 a.m., and so forth?

<html> <head>Harshal</head> <script> var limit="5:0" var doctitle = document.title var parselimit=limit.split(":") parselimit=parselimit[0]*60+parselimit[1]*1 function beginrefresh(){ if (parselimit==1) window.location.reload ...

Is memory allocated for 32 bits for variables with an undefined value in Javascript?

If I have a function with the signature below: function test(variable1, variable2) {} And I call it with only one parameter: test(5); Then within the test function, variable2 will be created but with a value of undefined. I'm interested to know if ...

Unlocking the potential for over 1000 search results using the GitHub API

Is there a way to display more than 1000 search results when listing the most starred Github repositories created in the last 30 days? I keep getting an error message that says: { "message": "Only the first 1000 search results are available", "documen ...