Invalid fields (do not contain anything)

Discussão em 'Angular' iniciado por Roxana, Fevereiro 5, 2025.

  1. Roxana

    Roxana Guest

    I am learning Angular with TypeScript. I am completely new to it. I have a form in html with different fields:


    <div class="container">
    <div class="form-container">
    <h2 class="form-title">Post New User</h2>
    <form>

    <div class="form-group" >
    <label for="nume">Nume: </label>
    <input type="text" id="nume" name="nume" formControlName="nume" required>
    </div>




    <div class="form-group" >
    <label for="email" >Email:</label>
    <input type="email" id="email" name="email" required formControlName="email" autocomplete="email">
    </div>



    <button type="submit" (click)="postUser()">Post</button>
    </form>
    </div>
    </div>



    This is my component

    import { Component } from '@angular/core';
    import { UserService } from '../../service/user.service';
    import { FormBuilder, Validators } from '@angular/forms';
    import { FormGroup } from '@angular/forms';
    import { ReactiveFormsModule } from '@angular/forms';
    import { CommonModule } from '@angular/common';
    @Component({
    selector: 'app-post-users',
    imports: [CommonModule],
    templateUrl: './post-users.component.html',
    styleUrl: './post-users.component.css'
    })
    export class PostUsersComponent {
    postUserForm!: FormGroup;
    constructor( private userrService:UserService,private fb:FormBuilder) { }
    ngOnInit(){
    this.postUserForm = this.fb.group({
    nume: ['', Validators.required],
    email: ['', [Validators.required, Validators.email]],


    });
    };

    postUser() {
    if (this.postUserForm.valid) {
    console.log('Formularul este valid!');
    const formData = this.postUserForm.value;
    console.log('Form Data:', formData);
    this.userrService.postUser(formData).subscribe((response) => {
    console.log(response);
    });
    } Object.keys(this.postUserForm.controls).forEach(field => {
    const control = this.postUserForm.get(field);
    if (control?.invalid) {
    console.log(`Câmp invalid: ${field}`, {
    errors: control.errors,
    value: control.value

    });
    debugger; }
    });


    }
    }






    The console message after I enter the data is the following "Invalid field: name

    {errors: {…}, value:''}

    errors: {required:true}

    value: ""

    [[Prototype]]: Object}

    I don't understand why the value is "" if I enter data in the text box. if I enter from postman, the data is entered into the database and a message appears in intelliJ that they have been entered. The problem is when I want to enter from the front, my data does not pass validation because they are ""

    Continue reading...

Compartilhe esta Página