The console error: I'm getting this error because the form seems to be requesting the data before I can get a value and it's rendering the component itself, I'm new to this technology, let me know if this is the way to do it or where should I look for the info any help would be great!
ERROR Error: Uncaught (in promise): TypeError: Cannot read properties of undefined (reading 'value')
TypeError: Cannot read properties of undefined (reading 'value')
at FormGroup.checkPassword (register.component.ts:30:59)
at FormGroup._runValidator (forms.mjs:2261:38)
at FormGroup.updateValueAndValidity (forms.mjs:2238:32)
at new FormGroup (forms.mjs:2641:14)
at FormBuilder.group (forms.mjs:7136:16)
at new RegisterComponent (register.component.ts:14:29)
at NodeInjectorFactory.RegisterComponent_Factory [as factory] (register.component.ts:32:4)
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
@Component({
selector: 'app-register',
templateUrl: './register.component.html',
styleUrls: ['./register.component.scss']
})
export class RegisterComponent implements OnInit {
register: FormGroup;
constructor(private fb: FormBuilder) {
this.register = this.fb.group({
usuario: ['', Validators.required],
password: ['', [Validators.required, Validators.minLength(4)]],
repeatPassword: ['']
}, { validator: this.checkPassword});
}
ngOnInit(): void {
}
userRegister(){
console.log(this.register)
}
checkPassword(group: FormGroup): any {
const pass = group.controls['password'].value;
const confirmPass = group.controls['confirmPassword'].value;
return console.log(pass,confirmPass);
}
}
<div >
<div >
<form [formGroup]="register" action="" (ngSubmit)="userRegister()">
<h1 >Sign-up</h1>
<div >
<input type="text" placeholder="Usuario" formControlName="usuario">
<span *ngIf="this.register.get('usuario')?.invalid && this.register.get('usuario')?.touched">El usuario requerido</span>
</div>
<div >
<input type="password" placeholder="Contraseña" formControlName="password">
<span *ngIf="this.register.get('password')?.invalid && this.register.get('password')?.touched">la contra es requerido</span>
</div>
<div >
<input type="password" placeholder="Contraseña" formControlName="repeatPassword">
</div>
<div >
<button type="submit" [disabled]="this.register.invalid" [class.invalid]="this.register.invalid">Entrar</button>
<button routerLink="/" >Volver</button>
</div>
<div >
<a routerLink="/register" >Crear cuenta</a>
</div>
</form>
</div>
</div>
Please help I truly don't know why it's happening
CodePudding user response:
You can use ?
to mark as optional to avoid reading value of undefined.
checkPassword(group: FormGroup): any {
const pass = group.controls['password']?.value;
const confirmPass = group.controls['confirmPassword']?.value;
// return console.log(pass,confirmPass);
console.log(pass,confirmPass);
return [pass, confirmPass];
}