Encountering an issue where trying to access 'errors' property results in undefined error in Angular 14 validation modifications

Initially, I had a functional code in Angular 12 implemented with a reactive form. When transitioning to Angular 14 for a new project, I researched the updated validation features and adjusted my code accordingly. However, upon testing, I encountered a series of errors as shown in the console:

Form value

{names: 'ddddddd', lastNames: 'sssssssssss', photoLocation: 'dddddd', married: 1, hasBrothersOrSisters: 0, …}
dateOfBirth
: 
"2023-01-07"
hasBrothersOrSisters
: 
0
lastNames
: 
"sssssssssss"
married
: 
1
names
: 
"ddddddd"
photoLocation
: 
"dddddd"

ERROR TypeError: Cannot read properties of undefined (reading 'errors')

success (indicating successful data save)

{idEmployee: 9, names: 'ddddddd', lastNames: 'sssssssssss', photoLocation: 'dddddd', married: 1, …}
dateOfBirth
: 
"2023-01-07T00:00:00"
hasBrothersOrSisters
: 
0
idEmployee
: 
9
lastNames
: 
"sssssssssss"
married
: 
1
names
: 
"ddddddd"
photoLocation
: 
"dddddd"
[[Prototype]]
: 
Object

ERROR TypeError: Cannot read properties of undefined (reading 'errors')

ERROR TypeError: Cannot read properties of undefined (reading 'errors')

Below is the corresponding HTML snippet

<div class="abs-center">
  <form [formGroup]="myForm" (ngSubmit)="onSubmit()">
   
    <!-- Form fields omitted for brevity -->

  </form>
</div>

Accompanying TypeScript (.ts) file

import { Component, OnInit } from '@angular/core';
// Additional imports and setup related to Angular forms

@Component({
  selector: 'app-save-employee',
  templateUrl: './save-employee.component.html',
  styleUrls: ['./save-employee.component.css']
})
export class SaveEmployeeComponent implements OnInit {

  // Properties and methods definitions here

}

Despite reviewing various examples, the issue persists. I made changes to handle potential null values more strictly. Could there be an element overlooked? Any thoughts or insights on this?

Answer №1

Take a look now and update your HTML template with this

You were mixing bracket and dot notation in the errors object

Replace this

form['names']?.errors?.[required]

With this form['names']?.errors?.required

<div class="abs-center">
  <form [formGroup]="myForm" (ngSubmit)="onSubmit()">

    <div class="form-group">
      <label>Names</label>
      <input type="text" class="form-control"
        formControlName="names"
        [ngClass]="{ 'is-invalid': submitted && form['names'].errors }"
      />
      <div *ngIf="submitted && form['names']?.errors" class="invalid-feedback">
        <div *ngIf="form['names']?.errors?.required">Names are required</div>
        <div *ngIf="form['names']?.errors?.minlength">Names must be at least 3 characters long</div>
        <div *ngIf="form['names']?.errors?.maxlength">Names must be a maximum of 30 characters long</div>
      </div>
    </div>

    <div class="form-group">
      <label>Last Names</label>
      <input
        type="text"
        formControlName="lastNames"
        class="form-control"
        [ngClass]="{ 'is-invalid': submitted && form['lastNames'].errors }"
      />
      <div *ngIf="submitted && form['lastNames']?.errors" class="invalid-feedback">
        <div *ngIf="form['lastNames'].errors?.required">Last names are required</div>
        <div *ngIf="form['lastNames'].errors?.minlength">Last names must be at least 3 characters long</div>
        <div *ngIf="form['lastNames'].errors?.maxlength">Last names must be a maximum of 30 characters long</div>
      </div>
    </div>

    <div class="form-group">
      <label>Photo Location</label>
      <input
        type="text"
        formControlName="photoLocation"
        class="form-control"
        [ngClass]="{ 'is-invalid': submitted && form['photoLocation'].errors }"
      />
      <div *ngIf="submitted && form['photoLocation']?.errors" class="invalid-feedback">
        <div *ngIf="form['photoLocation']?.errors?.required">Platform name</div>
        <div *ngIf="form['photoLocation']?.errors?.minlength">The platform name must be at least 3 characters long</div>
        <div *ngIf="form['photoLocation']?.errors?.maxlength">The platform name must be a maximum of 40 characters long</div>
      </div>
    </div>

    <div class="form-group">
        <div class="form-check">
          <input class="form-check-input" type="radio" id="radio1" [value]=1
          formControlName="married" >
          <label class="form-check-label" for="radio1">
            Married
          </label>
        </div>
        <div class="form-check">
          <input class="form-check-input" type="radio" id="radio2" [value]=0
          formControlName="married">
          <label class="form-check-label" for="radio2">
            Single
          </label>
        </div>
      </div>

    <div class="form-group">
      <div class="form-check">
        <input class="form-check-input" type="radio" id="exampleRadio1" [value]=0
        formControlName="hasBrothersOrSisters" >
        <label class="form-check-label" for="exampleRadio1">
          Has siblings
        </label>
      </div>
      <div class="form-check">
        <input class="form-check-input" type="radio" id="exampleRadio2" [value]=1
        formControlName="hasBrothersOrSisters">
        <label class="form-check-label" for="exampleRadio2">
          No siblings
        </label>
      </div>
    </div>

    <div class="form-group">
      <label>Date of Birth</label>
      <input
        type="date"
        formControlName="dateOfBirth"
        class="form-control"
        [ngClass]="{ 'is-invalid': submitted && form['formdateOfBirth'].errors }"
      />
      <div *ngIf="submitted && form['formdateOfBirth'].errors" class="invalid-feedback">
        <div *ngIf="form['formdateOfBirth'].errors?.required">Date of birth is required</div>
      </div>
    </div>

    <div class="form-group">

      <button type="submit" class="btn btn-primary">
        Save
      </button>

      <button type="button"  class="btn btn-warning float-right">
        Clear
      </button>

    </div>
  </form>
</div>

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

I encountered a conflict with the FOREIGN KEY constraint while attempting to execute the INSERT statement in the frontend application. However, the same statement successfully runs

I am currently developing a project using Angular for the frontend (Visual Studio Code) and .NET Core for the backend (Visual Studio). Everything seems to be functioning perfectly when I test the backend endpoints with Postman. However, I encountered an i ...

Creating a dynamic routerLink value in Angular 8 for items within an ngFor loop

I am currently attempting to route a dynamic value from the NgFor using [routerLink]. <li class="list-group-item d-flex justify-content-between align-items-center" *ngFor="let factors of factorsList"> <span>{{factors | ...

I am eager to learn how to integrate the "fs" module from Node.js into an Electron project powered by Angular

As I venture into writing my first desktop app using Electron and Angular5, I have encountered a roadblock while working with the fs module. Despite importing fs correctly (without errors in Visual Studio Code and with code completion), I faced an issue wh ...

What is the reason for the change event being triggered when a controlValueAccessor loses focus?

When I incorporate a custom input that implements the ControlValueAccessor interface into my template and bind to its change event like this: <input-app [value]="'initialVal'" (change)="onChange($event)"></input-app> My custom input ...

The string returned from the Controller is not recognized as a valid JSON object

When attempting to retrieve a string from a JSON response, I encounter an error: SyntaxError: Unexpected token c in JSON at position In the controller, a GUID is returned as a string from the database: [HttpPost("TransactionOrderId/{id}")] public asyn ...

What methods should I employ to effectively test a custom icon function?

I've written a function that creates a Leaflet icon with specified properties: createIcon( url, retinaUrl: string = null, height: number = 20, width: number = 20 ): Icon { const icon: Icon = L.icon({ iconUrl: url, ico ...

Collaborating on a project that has been developed using various editions of Typescript

Currently, I am part of a team working on a large project using Typescript in Visual Studio. As we have progressed through different versions of the project, we have encountered an issue with versioning the installed TypeScript within Visual Studio. Situa ...

Currently facing a challenge with my Laravel REST API Cors configuration while attempting to deploy to Vercel

I am encountering an error with my Laravel REST API CORS setup. Despite the fact that my API is functioning properly and I'm able to retrieve data correctly, there seems to be an issue with the 'Access-Control-Allow-Origin' header containing ...

What are the steps for integrating a custom fork of Angular Material into my Angular 6 application?

I am looking to customize the angular material2 source code and see those changes reflected in my angular 6 application. Currently, my app's package.json file specifies: “@angular/material”: “^6.4.3” I attempted to clone the project into a ...

Revolutionize Your Web Development with ASP.NET Core and Angular 2 Integration using Webpack

I have started a new ASP.NET Core 1.0.1 project and I am working on integrating Angular 2 from scratch with Webpack Module Bundler. My goal is to use Hot Module Replacement (HMR) through ASP.NET Core SpaServices in order to avoid browser reloads, but I am ...

The sliding hamburger menu children fail to move in unison with the parent

I'm currently working on a dynamic sliding navigation menu that activates when the hamburger icon is clicked. However, I am facing an issue where the child <a> elements are not sliding along with the parent div. You can see how it currently loo ...

Enhancing React Flow to provide updated selection and hover functionality

After diving into react flow, I found it to be quite user-friendly. However, I've hit a roadblock while attempting to update the styles of a selected node. My current workaround involves using useState to modify the style object for a specific Id. Is ...

The protractor-jasmine2-screenshot-reporter seems to be failing to generate the necessary screenshots within the designated folder

I have encountered an issue with my protractor.conf.js file and need some assistance. I have created the target/screenshots folder manually in the root of my angular-cli project, but when I run protractor conf.js, the protractor tests in the browser window ...

Unable to open Material Dialog after selecting marker in ngx-leaflet

I am currently utilizing the ngx-leaflet and ngx-leaflet-draw libraries to display a leaflet map. I have successfully displayed a marker on the map using the toolbar-marker-icon feature. My goal now is to show a Material Dialog Component when the marker is ...

What is the best way to activate an alert or swal function just once instead of repeatedly?

I am just starting to learn Angular. Currently, I have an application that contains two variables related to the status of financial transactions. These variables are: tab1TrxMessage, which holds any important messages, and tab1TrxStatus that indicates wh ...

What is the best way to export a default object containing imported types in TypeScript?

I am currently working on creating ambient type definitions for a JavaScript utility package (similar to Lodash). I want users to be able to import modules in the following ways: // For TypeScript or Babel import myutils from 'myutils' // myuti ...

Issue with Angular 6: Struggling to Implement DatePipe

I am trying to set the current date within a formGroup in a specific format, but I keep encountering an error with the code below: 'Unable to convert "13/07/2020" into a date' for pipe 'DatePipe' this.fb.group({ startdateActivi ...

Revamping every Angular component

Looking for a shortcut to upgrade all my Angular components at once. When checking my Angular version with ng v globally in VS Code terminal, results differ between overall and project directory settings: https://i.stack.imgur.com/2iOJx.png https://i.st ...

What is the best way to retrieve the global styles.scss file from the assets folder for privacy, legal, and conditions pages

I have a static page called terms.html located at: $PROJECT_ROOT/src/assets/html/terms.html In addition, my global styles (used by all components) are found at: $PROJECT_ROOT/src/styles.scss To include the static html file in a component, I use the fol ...

User interface for dynamically generated elements using Typescript with React

Looking to create a translator hook that can pull language json files based on the selected language and return a portion of this large object depending on the arguments provided. How can I create an interface for an object that has been dynamically create ...