Home > Net >  Cannot read properties of undefined (reading 'errors') after adapting validation for Angul
Cannot read properties of undefined (reading 'errors') after adapting validation for Angul

Time:01-12

I have a code that works on Angular 12, it is a reactive form, now I am making a form on Angular 14, I read about new validation and I made the arrangements, but I am getting errors, this is the secuence on 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 (Which means that the data was saved)

{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')

This is the html

<div >
  <form [formGroup]="myForm" (ngSubmit)="onSubmit()">
   
    <div >
      <label>Nombres</label>
      <input type="text" 
        formControlName="names"        
        [ngClass]="{ 'is-invalid': submitted && form['names'].errors }"
      />
      <div *ngIf="submitted && form['names'].errors" >
        <div *ngIf="form['names'].errors?.['required']">Los nombres son requeridos</div>
        <div *ngIf="form['names'].errors?.['minlength']">Los nombres deben ser mínimo de 3 caracteres</div>
        <div *ngIf="form['names'].errors?.['maxlength']">Los nombres deben ser de máximo de 30 caracteres</div>
      </div>
    </div>

    <div >
      <label>Apellidos</label>
      <input
        type="text"
        formControlName="lastNames"
        
        [ngClass]="{ 'is-invalid': submitted && form['lastNames'].errors }"
      />
      <div *ngIf="submitted && form['lastNames'].errors" >
        <div *ngIf="form['lastNames'].errors?.['required']">Los apellidos son requeridos</div>
        <div *ngIf="form['lastNames'].errors?.['minlength']">Los apellidos deben ser mínimo de 3 caracteres</div>
        <div *ngIf="form['lastNames'].errors?.['maxlength']">Los apellidosdeben ser de máximo de 30 caracteres</div>
      </div>
    </div>

    <div >
      <label>Ubicación de la foto</label>
      <input
        type="text"
        formControlName="photoLocation"
        
        [ngClass]="{ 'is-invalid': submitted && form['photoLocation'].errors }"
      />
      <div *ngIf="submitted && form['photoLocation'].errors" >
        <div *ngIf="form['photoLocation'].errors?.['required']">Platform name</div>
        <div *ngIf="form['photoLocation'].errors?.['minlength']">El platform name debe ser mínimo de 3 caracteres</div>
        <div *ngIf="form['photoLocation'].errors?.['maxlength']">El platform name ser de máximo de 40 caracteres</div>
      </div>
    </div>      

    <div >
        <div >
          <input  type="radio" id="radio1" [value]=1 
          formControlName="married" >
          <label  for="radio1">
            Casado
          </label>
        </div>
        <div >
          <input  type="radio" id="radio2" [value]=0 
          formControlName="married">
          <label  for="radio2">
            Soltero
          </label>
        </div> 
      </div>

    <div >
      <div >
        <input  type="radio" id="exampleRadio1" [value]=0 
        formControlName="hasBrothersOrSisters" >
        <label  for="exampleRadio1">
          Tiene hermanos
        </label>
      </div>
      <div >
        <input  type="radio" id="exampleRadio2" [value]=1 
        formControlName="hasBrothersOrSisters">
        <label  for="exampleRadio2">
          No tiene
        </label>
      </div> 
    </div>

    <div >
      <label>Fecha de nacimiento</label>
      <input
        type="date"
        formControlName="dateOfBirth"
        
        [ngClass]="{ 'is-invalid': submitted && form['formdateOfBirth'].errors }"
      />
      <div *ngIf="submitted && form['formdateOfBirth'].errors" >
        <div *ngIf="form['formdateOfBirth'].errors?.['required']">La fecha de nacimiento es requerida</div>
      </div>
    </div>

    <div >
      
      <button type="submit" >
        Guardar
      </button>

      <button type="button" (click)="onReset()" >
        Limpiar
      </button>
      
    </div>
  </form>
</div>

the .ts

import { Component, OnInit } from '@angular/core';
import { AbstractControl, FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Employee } from '../data/employee';
import { EmployeeServiceService } from '../data/employee-service.service';
import { ReactiveFormsModule } from '@angular/forms';
import { FormsModule } from '@angular/forms';

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

  myForm!: FormGroup;    
  submitted = false; 

  constructor(private formBuilder: FormBuilder, private employeeService: EmployeeServiceService) { }

  iniciarFormulario(){
    this.myForm = this.formBuilder.group({                     
      names: ['', [Validators.required, Validators.minLength(3), Validators.maxLength(30)]],
      lastNames: ['', [Validators.required, Validators.minLength(3), Validators.maxLength(30)]],
      photoLocation: ['', [Validators.required, Validators.minLength(3), Validators.maxLength(40)]],
      married: ['', [Validators.required]],
      hasBrothersOrSisters: ['', [Validators.required]],                     
      dateOfBirth: ['', [Validators.required]]      
    });
}

  ngOnInit(): void {
    this.iniciarFormulario();
  }

  get form(): { [key: string]: AbstractControl; }
  {
      return this.myForm.controls;
  }

  onReset(): void {
    this.submitted = false;
    this.myForm.reset();
  }

  onSubmit() {    
    this.submitted = true;
    console.log("Form value ", this.myForm.value);

    if (this.myForm.invalid) {
      console.log('Error')          
      return
    }     

    this.employeeService.SaveEmployee(this.myForm.value).subscribe(              
                 result => console.log('success ', result),                 
                 error => console.log('error ', error)                 
             );                 
  }  
 

}

I have been reading examples in case I have something missing, but everything seems to be ok.

I changed errors: errors?.

I thought maybe Angular is more strict with null values.

Is there something missing?

CodePudding user response:

Check it now replace your Html template with this

You were using bracket and dot notation both on errors object

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

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

<div >
  <form [formGroup]="myForm" (ngSubmit)="onSubmit()">

    <div >
      <label>Nombres</label>
      <input type="text" 
        formControlName="names"
        [ngClass]="{ 'is-invalid': submitted && form['names'].errors }"
      />
      <div *ngIf="submitted && form['names']?.errors" >
        <div *ngIf="form['names']?.errors?.required">Los nombres son requeridos</div>
        <div *ngIf="form['names']?.errors?.minlength">Los nombres deben ser mínimo de 3 caracteres</div>
        <div *ngIf="form['names']?.errors?.maxlength">Los nombres deben ser de máximo de 30 caracteres</div>
      </div>
    </div>

    <div >
      <label>Apellidos</label>
      <input
        type="text"
        formControlName="lastNames"
        
        [ngClass]="{ 'is-invalid': submitted && form['lastNames'].errors }"
      />
      <div *ngIf="submitted && form['lastNames']?.errors" >
        <div *ngIf="form['lastNames'].errors?.required">Los apellidos son requeridos</div>
        <div *ngIf="form['lastNames'].errors?.minlength">Los apellidos deben ser mínimo de 3 caracteres</div>
        <div *ngIf="form['lastNames'].errors?.maxlength">Los apellidosdeben ser de máximo de 30 caracteres</div>
      </div>
    </div>

    <div >
      <label>Ubicación de la foto</label>
      <input
        type="text"
        formControlName="photoLocation"
        
        [ngClass]="{ 'is-invalid': submitted && form['photoLocation'].errors }"
      />
      <div *ngIf="submitted && form['photoLocation']?.errors" >
        <div *ngIf="form['photoLocation']?.errors?.required">Platform name</div>
        <div *ngIf="form['photoLocation']?.errors?.minlength">El platform name debe ser mínimo de 3 caracteres</div>
        <div *ngIf="form['photoLocation']?.errors?.maxlength">El platform name ser de máximo de 40 caracteres</div>
      </div>
    </div>

    <div >
        <div >
          <input  type="radio" id="radio1" [value]=1
          formControlName="married" >
          <label  for="radio1">
            Casado
          </label>
        </div>
        <div >
          <input  type="radio" id="radio2" [value]=0
          formControlName="married">
          <label  for="radio2">
            Soltero
          </label>
        </div>
      </div>

    <div >
      <div >
        <input  type="radio" id="exampleRadio1" [value]=0
        formControlName="hasBrothersOrSisters" >
        <label  for="exampleRadio1">
          Tiene hermanos
        </label>
      </div>
      <div >
        <input  type="radio" id="exampleRadio2" [value]=1
        formControlName="hasBrothersOrSisters">
        <label  for="exampleRadio2">
          No tiene
        </label>
      </div>
    </div>

    <div >
      <label>Fecha de nacimiento</label>
      <input
        type="date"
        formControlName="dateOfBirth"
        
        [ngClass]="{ 'is-invalid': submitted && form['formdateOfBirth'].errors }"
      />
      <div *ngIf="submitted && form['formdateOfBirth'].errors" >
        <div *ngIf="form['formdateOfBirth'].errors?.required">La fecha de nacimiento es requerida</div>
      </div>
    </div>

    <div >

      <button type="submit" >
        Guardar
      </button>

      <button type="button"  >
        Limpiar
      </button>

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

CodePudding user response:

When editing with search and replace, this name was wrong: formdateOfBirth, it is just dateOfBirth. This is the one who was giving error messsages. Thanks @Shakir

  • Related