An issue has occurred with attempting to access the 'phone' property of a null value. This error is at the root of the problem and needs to

I have implemented a function to retrieve all clients from an API:

  this.ws.getallclients().subscribe(
  client => {
    this.client = client.map((clients) => {
      this.filteredOptions = this.addsale.controls['client_id'].valueChanges.pipe(
        startWith(''),
        map(val => this._filter(val))
      );
      return new Client(clients);
    });
    if (this.ss.getData('client_id')) {
      const client_id = this.ss.getData('client_id');
      this.addsale.controls.client_id.setValue(client_id)
      let selectedClient = new Client('')
      this.selectedClient = null;
      for (let i = 0; i < client.length; i++) {
        if (client[i].client_id === client_id) {
          this.selectedClient = client[i];
        }
      }
    }
  }
);

An error is being displayed as follows:

ERROR TypeError: Cannot read property 'phone' of null at Object.eval [as updateRenderer]

This error occurs because the value `client[i].client_id` returns a numeric ID like 123456, while it should display the name of the client such as "MyName". This mismatch causes the issue in the following HTML code:

Here is the relevant html code snippet:

<fieldset>
<legend>Client Data</legend>
        <div class="input-field col s4">
        <input formControlName="client_id" id="client_id"   matInput placeholder="Select Client*" aria-label="State" [matAutocomplete]="auto" >
    <mat-autocomplete autoActiveFirstOption #auto="matAutocomplete" [displayWith]="displayFn">
      <mat-option (onSelectionChange)="onSelect(item.client_id)" *ngFor="let item of filteredOptions | async" [value]="item.name">
        {{item.name}}
      </mat-option>
    </mat-autocomplete>
</div>
   <div class="input-field col s12">
    ID Number:
     <span style="color:darkblue">{{selectedClient.phone}}</span>
     </div>
 </fieldset>

Any suggestions on how to resolve this error?

Answer №1

The issue lies in your code where this.selectedClient = null is set when there is no selected client, and then the template tries to access selectedClient.phone, resulting in an error. To address this, you can consider replacing the following lines:

  let selectedClient = new Client('')
  this.selectedClient = null;

with:

  this.selectedClient = new Client('')

This way, you will have a blank Client object in such scenarios. Alternatively, if you prefer to avoid evaluating the problematic part of the template when selectedClient is not available, you may want to explore using ngIf. Though I am not familiar with Angular, based on a quick review of the documentation, the following approach could potentially resolve the issue:

<span *ngIf="selectedClient" style="color:darkblue">{{selectedClient.phone}}</span>

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

Having trouble resolving npm install -g @angular/cli due to issue with checking the installable status of [email protected] module

When attempting to install @angular/cli using the npm command in the command prompt, I encountered an issue with resolveWithNewModule. It seems to be stuck at checking installable status.[email protected] ...

Discover the step-by-step guide to setting up forwarding in React Router 5

Just diving into the world of React and TypeScript. I'm working with a component called Err. Is there a way to redirect it using React Router 5? import React, { FC, Fragment, useEffect } from "react"; const Err: FC<{ error: string }> = ({ erro ...

Error in Typescript: Cannot assign type 'string[]' to type 'string'

I'm currently developing a project using Next.js with Typescript and .tsx files, and I'm utilizing Supabase as my database. While everything is functioning perfectly on localhost, I'm encountering an issue when trying to build the project o ...

Ways to initiate an HTTP request within switchMap upon emission of a BehaviorSubject value

As I delve into writing angular applications in a declarative style, I find myself pondering on the most effective approach for handling POST requests. Specifically, I am facing a dilemma with regards to calling these requests when dealing with a login for ...

Unveiling the Mystery of Angular: Why are constructor parameters without access specifiers hidden from view outside the

When I explicitly set an access specifier for a constructor parameter, it becomes visible outside the constructor. For example: constructor(private employeResourceService:EmployeeResourceService ){ //code} ngOnInit(){ this.employeResourceService=unde ...

Why is my RxJS timer not waiting for the specified time?

I'm diving into the world of RxJS and trying to grasp its concepts. During some testing, I encountered a puzzling issue that has me stumped. Below is the snippet in question : let item = { id: 1, name: 'chair' }; const asyncItem = timer(20 ...

Dynamic Angular Menu

Is there a cleaner, more dynamic way to implement a mat menu with individual click values and disable properties for each button? I want to avoid repeating code like in the example below. Looking for a more dynamic solution. #code <mat-menu #createDeal ...

Exploring techniques to iterate through this specific JSON data within an Angular frontend

I am looking for assistance in looping the data below into a 'Select dropdown' using Angular 10. The data consists of all the States in India along with their districts. I have retrieved this information from the internet, but I am unsure how to ...

What is the best way to choose a particular radio button from a group of radio buttons using typescript?

Is there a way to automatically select a specific radio button when an item is chosen from a dropdown menu on the webpage using a TypeScript function that is triggered by the dropdown selection? ...

Fairly intricate React function component declaration with TypeScript

const withAuth = () => <OriginalProps extends {}>( Component: React.ComponentType<OriginalProps & IAuthContextInterface> ) => { } (withAuth()(PrivateRoute)) // this is how the HOC called Could someone simplify what this function d ...

Experiencing a useContext error when implementing MDX with NextJS 13

I am currently working on integrating mdx files into Next.js 13. After completing all necessary configurations in next.config and creating the file structure, I have the following path within the app folder: > docs > components > accordion > pa ...

How to Validate Ionic 2 Radio Button Selections with TypeScript

Imagine having a list like the one shown below: <ion-list radio-group [(ngModel)]="autoManufacturers"> <ion-list-header> Auto Manufacturers </ion-list-header> <ion-item> <ion-label>Cord</ion-label> &l ...

React Typescript: Turn off spellchecking

Struggling to turn off spell check for typescript <form> <input type='text' name='accountName' ref={accountName} onChange={checkName} spellCheck='false' // <====== Disable spellche ...

@ngrx effects ensure switchmap does not stop on error

Throughout the sign up process, I make 3 http calls: signing up with an auth provider, creating an account within the API, and then logging in. If the signup with the auth provider fails (e.g. due to an existing account), the process still tries to create ...

Ways to implement a loading template with OnPush change detection technique

Currently, I am retrieving a route parameter: searchResults$: Observable<string[]>; constructor( private route: ActivatedRoute, private svc: SearchService) { this.searchResults$ = this.route.paramMap.pipe( map((p: ParamMap) => p.get(&a ...

Exploring Local Gems with Google Places API in Ionic 2

I recently integrated the Google Maps API into my app and now I am looking to incorporate Google Places as well. I have managed to successfully implement Geolocation, but I am facing difficulties when trying to perform a nearby search for "supermarkets" in ...

Achieving JSON element sorting in the most effective way

https://i.stack.imgur.com/NQbdN.png Each array contains the following information: {{ id: 39, treaty_number: "qwe", insurant_name: "222", belonging_to_the_holding_company: "test", date_start: "2016-04-15", etc }} Is there a way to sort each array in asc ...

The ng-model used within an *ngFor loop is not displaying the correct value

I am working with a JSON file in my Angular2 App. The specific JSON object I am referring to is named tempPromotion and I am trying to access the data within ['results'] like this: tempPromotion['response_payload']['ruleset_list ...

Issue found in VS2015 with the sequence of AngularJS TypeScript ts files within the appBundle.js file

I've been diving into AngularJS and TypeScript with the VS2015 RC Cordova TypeScript project. Recently, I created a "MyController.ts" file in the same folder as "index.ts". The code worked perfectly fine: module MyTestApp{ export class MyContro ...

Mastering the art of shaping state in NGRX for the master-detail pattern

Imagine a scenario where I am developing a compact app for organizing tasks. This app makes use of angular and NGRX to efficiently manage the state. Each day, the user loads tasks in the morning and then travels to different locations to complete them. Th ...