Runtime error: Angular property is null

I've set up the following structure:

export class HomePageComponent implements OnInit {
  constructor(private httpClient: HttpClient) {
  }

 nummer: FormControl = new FormControl("", this.nummerValidator());

  firstname: FormControl = new FormControl("", [Validators.minLength(3)]);
  lastname: FormControl = new FormControl("", [Validators.minLength(3)]);

 formGroup: FormGroup = new FormGroup({
    firstname: this.firstname,
    lastname: this.lastname,
  }, this.formGroupValidator());

 ngOnInit() {
  }

 nummerValidator() {
    return (control: FormControl): { [key: string]: any } | null => {
      if (this.checkEmpty(control.value)) {
        this.enableOnNumber();
        return null;
      }
      this.disableOnNumber();
      if (isNaN(control.value)) {
        return {'forbiddenName': {value: control.value}};
      }
      return null;
    }
  }

 enableOnNumber() {
    this.firstname.enable();
    this.lastname.enable();
  }

  disableOnCardNumber() {
    this.firstname.disable();
    this.lastname.disable();
  }

formGroupValidator() {
    return (control: FormGroup): { [key: string]: any } | null => {
      //someStuffHere
      return errorFound ? {'formGroupError': true} : null;
    }
  }

Upon loading the page with this setup, an error occurs stating that this.firstname and this.lastname are null within the enableOnNumber function. This issue does not exist with the disableOnNumber function.

Strangely, when I initialize the nummer FormControl without the validator and add the validator in the ngOnInit function, everything functions correctly. Why does this approach work? Can anyone shed some light on this?

Here is the revised approach:

nummer: FormControl = new FormControl();
ngOnInit() {
    this.nummer.validator = this.NummerValidator();
  }

Answer №1

TypeScript is a language that extends JavaScript with static typing and compiles down to regular JavaScript. On the other hand, JavaScript is an interpreted language, meaning that an interpreter in the browser processes and executes the code line by line.

On page load, the nummerValidator() function calls the enableOnNumber() method, which is responsible for validating the nummer control. Since the nummer form control is declared first, its validation is performed initially.

To make a necessary change, implement the following code snippet:

  firstname: FormControl = new FormControl('', [Validators.minLength(3)]);
  lastname: FormControl = new FormControl('', [Validators.minLength(3)]);
  nummer: FormControl = new FormControl('', this.nummerValidator());

To avoid potential issues with nummer validation, it's recommended to declare firstname and lastname form controls before nummer form control.

If the paybackNummerValidator() method relies on firstname and lastname, make sure to include appropriate null checks to prevent any errors from occurring.

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

Poorly packaged library - Custom Angular library - Node Package Manager

Recently, I've been delving into the process of publishing a simple Angular library on NPM. Despite following various tutorials (like those found here, here, and here), I faced difficulties when attempting to use it in a test project. MY JOURNEY In s ...

What could be causing my Angular project to not run properly without any changes made after creating a new component that I want to include in app.component.html?

Greetings, I am just starting out with Angular 17 and I am currently going through the Tour of Heroes course on the official website. Following the tutorial's instructions, I created a new component called 'heroes' after setting up my projec ...

In TypeScript, combining the numbers 0 and 1 results in the value 01

I am in the process of developing a Shopping Card feature. private _card: Map<Product, number> = new Map<Product, number>(); ... addToCard(prod: Product, amount: number = 1): void { const totalAmount: number = this._card.get(prod) + amou ...

Angular-Serviceworker: The start URL fails to return a 200 status code when offline

Recent Versions "@angular/common": "~9.0.0" "@angular/service-worker": "~9.0.0" Exploration Utilizing the service-worker was achieved by executing ng add @angular/pwa --project [app] which triggered Lighthouse to acknowledge the web-app as a PWA. Howev ...

What is the best way to leverage TypeScript for destructuring from a sophisticated type structure?

Let's consider a scenario where I have a React functional component that I want to implement using props that are destructured for consistency with other components. The component in question is a checkbox that serves two roles based on the amount of ...

Setting a Default Value for Angular Material Date Range Picker

My goal is to determine the default month that the date-picker opens up on, based on values obtained from a calendar event. For instance, if it's currently April and I click to the next month on the calendar, when I select the date-picker, it should o ...

Rotate object within HTML table

I have a simple data structure as shown below: [ { "ClientId": 512, "ProductId": 7779, "Date": "2019-01-01", "Quantity": 20.5, "Value": 10.5 }, { "ClientId": 512, "ProductId": ...

Using Typescript to define property types based on their respective values

Is it possible to set a property type based on the property value? For example, if the command is: If 'set' then the payload must be PayloadSet If 'put' then the payload must be PayloadPut If 'del' then the payload must be ...

"Displaying the Material Input TextBox in a striking red color when an error occurs during

After referring to the links provided below, I successfully changed the color of a textbox to a darkish grey. Link 1 Link 2 ::ng-deep .mat-form-field-appearance-outline .mat-form-field-outline { color: #757575!important; } Although this solved the ...

Oops! Looks like we hit a dead end. The URL Segment "in Angular 13" doesn't

In my coding project I have two classes named Fichier and Dossier. The goal is to display the details of files based on the file's id. So, whenever a file is clicked, I want to show a detail page specific to that file. Below is the code snippet for ac ...

Attempting to incorporate alert feedback into an Angular application

I am having trouble referencing the value entered in a popup input field for quantity. I have searched through the documentation but haven't found a solution yet. Below is the code snippet from my .ts file: async presentAlert() { const alert = awa ...

Is there an issue with type guards not functioning as expected within async functions in Typescript?

As I work on implementing an authentication function for user roles using TypeScript and Firebase/Store, I've come across a peculiar issue related to type guards in async functions, especially with the use of .then(). Here is a brief snippet showcasi ...

The element 'mat-form-field' is unrecognized and not found in the document:

I'm facing an issue with my Angular app that utilizes Materials. I have imported MatFormFieldModule in my materials.module.ts file, but for some reason, it's not being recognized. All other material components are functioning properly except for ...

Identifying the absence of a character at the end of the last line in Node.js to detect

Currently, I am processing data line by line from a buffer. Within the buffer, the data is structured as follows: name,email,phn test1,<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="47332234337607223f262a372b226924282a">[em ...

Pass along a JSON array from Express to Angular2

I have been working on sending a custom array filled with mongoose errors, and I am successfully creating the array. Below is the code snippet: student.save(function(err, student) { if(err) var errors = []; for (field in err.errors) { ...

The issue persists in VSCode where the closing brackets are not being automatically added despite

Recently, I've noticed that my vscode editor is failing to automatically add closing brackets/parenthesis as it should. This issue only started happening recently. I'm curious if anyone else out there has encountered this problem with their globa ...

Single-use binding format

I am a beginner with Angular and I have some doubts about the syntax used in Angular. In AngularJS, we can achieve one-time binding like this: <p>{{::myVar}}</p> In Angular, I know we can do it differently. <p [innerText]="myVar"></ ...

Windows drive letter casing error when using Yarn and NextJS

Today, I set up a fresh project using Yarn and NextJS on my Windows computer. When I try to start the project, I encounter an error stating that the casing is "invalid" for the project directory. The specific errors I am facing are: Invalid casing detecte ...

The SrollToTop function is ineffective when used with a component in Ionic 6/Angular

Recently, I implemented a fabbutton feature that allows users to scroll to the top of a page with just one click. Initially, I tested this functionality without using it as a component, and everything worked perfectly. However, now I want to turn this fabb ...

Creating a Jest TypeScript mock for Axios

Within a class, I have the following method: import axios from 'axios' public async getData() { const resp = await axios.get(Endpoints.DATA.URL) return resp.data } My aim is to create a Jest test that performs the following actions: jes ...