Angular 9 Многострочная динамика c проверка формы - PullRequest
0 голосов
/ 19 июня 2020

Я создал простую динамику c, когда количество строк выбирается из раскрывающегося списка, строки создаются с отображением ошибки проверки в каждом поле. Может ли кто-нибудь помочь мне отобразить ошибку проверки для всех строк в одном месте , что означает, что она проверяет все поля в строках, а ошибка проверки для конкретного поля отображается только один раз под формой.

Вот мой код: app.component.ts

import { Component } from '@angular/core';
import { FormBuilder, FormGroup, FormArray, Validators } from '@angular/forms';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'employeelist';
  buttonstatus = false;
  isSubmitted = '';
  submitted = false;
  userTable: FormGroup;
  control: FormArray;
  employeelist: any = [];
  selectedGroup: any;
  counts = [{
    "id": 1,
    "name": "One"
  },
  {
    "id": 2,
    "name": "Two"
  },
  {
    "id": 3,
    "name": "Three"
  },
  {
    "id": 4,
    "name": "Four"
  },
  {
    "id": 5,
    "name": "Five"
  }
  ];
  constructor(private fb: FormBuilder) { }

  ngOnInit(): void {
    this.userTable = this.fb.group({
      tableRows: this.fb.array([])
    });
  }

  initiateForm(): FormGroup {
    return this.fb.group({
      firstname: ['', [Validators.required, Validators.minLength(3)]],
      lastname: ['', [Validators.required, Validators.minLength(1)]],
      email: ['', [Validators.required, Validators.pattern("^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$")]],
      dob: ['', [Validators.required]],
      mob: ['', [Validators.required, Validators.pattern("^((\\+91-?)|0)?[0-9]{10}$")]],
      isEditable: [false]
    });
  }

  get getFormControls() {
    const control = this.userTable.get('tableRows') as FormArray;
    return control;
  }

  addRow() {
    if (this.selectedGroup) {
      let control = this.userTable.get('tableRows') as FormArray;
      var count = this.selectedGroup.id;
      for (let i = 0; i < count; i++) {
        control.push(this.initiateForm());
      }

      this.buttonstatus = true;
      this.isSubmitted = 'true';
    }
    else {
      this.isSubmitted = 'false';
    }
  }

  deleteRow(index: number) {
    const control = this.userTable.get('tableRows') as FormArray;
    control.removeAt(index);
    if (control.length == 0) {
      this.buttonstatus = false;
    }
  }

  doneRow(group: FormGroup) {
    if (group.valid) {
      group.get('isEditable').setValue(true);
    }
  }

  onSubmit() {
    this.submitted = true;
    if (this.userTable.invalid) {
      return;
    }

    // display form values on success
    alert('SUCCESS!! :-)\n\n' + JSON.stringify(this.userTable.value));
    this.employeelist = this.userTable.value;
  }
}

app.component. html

<div class="container">
    <h1>Employee List</h1>

    <div class="card">
        <div class="card-header">
            Employee
            <div class="input-group mb-3">
                <select class="custom-select" [(ngModel)]="selectedGroup" [disabled]='buttonstatus'>
                    <option *ngFor="let item of counts" [ngValue]="item">{{item.name}}</option>
                </select>
                <div class="input-group-append">
                    <button (click)="addRow()" [disabled]='buttonstatus' class="btn btn-outline-secondary"
                        type="button"> GO </button>
                </div>
            </div>
            <div class="invalid" *ngIf="isSubmitted == 'false'">
                <sup>*</sup>Please select the no. of employees
            </div>
        </div>
        <div class="card-body">
            <form [formGroup]="userTable" (ngSubmit)="onSubmit()">
                <table class="table table-striped table-bordered">
                    <thead>
                        <tr>
                            <th>#</th>
                            <th>First Name</th>
                            <th>Last Name</th>
                            <th>Email</th>
                            <th>DOB</th>
                            <th>Mobile</th>
                            <th></th>
                        </tr>
                    </thead>
                    <tbody>
                        <ng-container formArrayName="tableRows"
                            *ngFor="let group of getFormControls.controls; let i=index">
                            <tr [formGroupName]="i">
                                <th>{{i+1}}</th>
                                <td><input type="text" required formControlName="firstname"
                                        class="form-control input-sm"
                                        [ngClass]="{ 'is-invalid': (submitted || getFormControls.controls[i].get('firstname').touched) && getFormControls.controls[i].get('firstname').errors }" />
                                    <div *ngIf="((submitted || getFormControls.controls[i].get('firstname').touched) &&  getFormControls.controls[i].get('firstname').errors)"
                                        class="invalid-input">
                                        <div *ngIf="getFormControls.controls[i].get('firstname').errors.required">First
                                            Name is required</div>
                                        <div *ngIf="getFormControls.controls[i].get('firstname').errors.minlength">First
                                            Name must be at least 3 characters</div>
                                    </div>
                                </td>
                                <td><input type="text" required class="form-control input-sm" formControlName="lastname"
                                        [ngClass]="{ 'is-invalid': (submitted || getFormControls.controls[i].get('lastname').touched) && getFormControls.controls[i].get('lastname').errors }" />
                                    <div *ngIf="((submitted || getFormControls.controls[i].get('lastname').touched) &&  getFormControls.controls[i].get('lastname').errors)"
                                        class="invalid-input">
                                        <div *ngIf=" getFormControls.controls[i].get('lastname').errors.required">Last
                                            Name is required</div>
                                        <div *ngIf="getFormControls.controls[i].get('lastname').errors.minlength">Last
                                            Name must be at least 1 characters</div>
                                    </div>
                                </td>
                                <td><input type="email" class="form-control input-sm" required formControlName="email"
                                        [ngClass]="{ 'is-invalid': (submitted || getFormControls.controls[i].get('email').touched) && getFormControls.controls[i].get('email').errors }" />
                                    <div *ngIf="((submitted || getFormControls.controls[i].get('email').touched) &&  getFormControls.controls[i].get('email').errors)"
                                        class="invalid-input">
                                        <div *ngIf=" getFormControls.controls[i].get('email').errors.required">Email is
                                            required</div>
                                        <div *ngIf=" getFormControls.controls[i].get('email').errors.pattern">Enter
                                            Valid Email</div>
                                    </div>
                                </td>
                                <td><input type="date" class="form-control input-sm" required formControlName="dob"
                                        [ngClass]="{ 'is-invalid': (submitted || getFormControls.controls[i].get('dob').touched) && getFormControls.controls[i].get('dob').errors }" />
                                    <div *ngIf="((submitted || getFormControls.controls[i].get('dob').touched) &&  getFormControls.controls[i].get('dob').errors)"
                                        class="invalid-input">
                                        <div *ngIf=" getFormControls.controls[i].get('dob').errors.required">Date of
                                            Birth is required</div>
                                    </div>
                                </td>
                                <td><input type="tel" class="form-control input-sm" required formControlName="mob"
                                        [ngClass]="{ 'is-invalid': (submitted || getFormControls.controls[i].get('mob').touched) && getFormControls.controls[i].get('mob').errors }" />
                                    <div *ngIf="((submitted || getFormControls.controls[i].get('mob').touched) &&  getFormControls.controls[i].get('mob').errors)"
                                        class="invalid-input">
                                        <div *ngIf=" getFormControls.controls[i].get('mob').errors.required">Mobile
                                            no is required</div>
                                        <div *ngIf=" getFormControls.controls[i].get('mob').errors.pattern">Enter Valid
                                            Mobile No</div>
                                    </div>
                                </td>
                                <td>
                                    <!-- <input type="button" class="btn btn-outline-success mr-1" value="Submit" (click)="doneRow(group)" /> -->
                                    <input type="button" class="btn btn-outline-danger" value="Delete"
                                        (click)="deleteRow(i)" />
                                </td>
                            </tr>                            
                        </ng-container>
                    </tbody>
                </table>
                <button type="submit" class="btn btn-outline-primary" [disabled]='!buttonstatus'>Submit</button>
            </form>
        </div>
    </div>
</div>

Скриншот ошибки проверки здесь

Пожалуйста, попросите вашей помощи в отображении ошибок проверки в отдельном списке, пронумерованном под формой. Например: если есть три строки и единственная ошибка проверки имени в одной строке и если ее фамилия и Ошибка проверки электронной почты в другом и третьем не имеет ошибок проверки. Могу ли я отображать такие ошибки проверки, вместо отображения ошибки в каждом поле, как показано на снимке экрана:

  1. Требуется имя
  2. Требуется фамилия
  3. Требуется электронная почта

Любая помощь будет отличной, заранее благодарю вас. * 1 025 *

1 Ответ

0 голосов
/ 24 июня 2020

Проверочное изображение

<div class="container">
    <h1>Employee List</h1>

    <div class="card">
        <div class="card-header">
            Employee
            <div class="input-group mb-3">
                <select class="custom-select" [(ngModel)]="selectedGroup" [disabled]='buttonstatus'>
                    <option *ngFor="let item of counts" [ngValue]="item">{{item.name}}</option>
                </select>
                <div class="input-group-append">
                    <button (click)="addRow()" [disabled]='buttonstatus' class="btn btn-outline-secondary" type="button"> GO </button>
                </div>
            </div>
            <div class="invalid" *ngIf="isSubmitted == 'false'">
                <sup>*</sup>Please select the no. of employees
            </div>
        </div>
        <div class="card-body">
            <form [formGroup]="userTable" (ngSubmit)="onSubmit()">
                <table class="table table-striped table-bordered">
                    <thead>
                        <tr>
                            <th>#</th>
                            <th>First Name</th>
                            <th>Last Name</th>
                            <th>Email</th>
                            <th>DOB</th>
                            <th>Mobile</th>
                            <th></th>
                        </tr>
                    </thead>
                    <tbody>
                        <ng-container formArrayName="tableRows" *ngFor="let group of getFormControls.controls; let i=index">
                            <tr [formGroupName]="i">
                                <th>{{i+1}}</th>
                                <td><input type="text" required formControlName="firstname" class="form-control input-sm" />
                                </td>
                                <td><input type="text" required class="form-control input-sm" formControlName="lastname" />
                                </td>
                                <td><input type="email" class="form-control input-sm" required formControlName="email" />
                                </td>
                                <td><input type="date" class="form-control input-sm" required formControlName="dob" />
                                </td>
                                <td><input type="tel" class="form-control input-sm" required formControlName="mob" />
                                </td>
                                <td>
                                    <!-- <input type="button" class="btn btn-outline-success mr-1" value="Submit" (click)="doneRow(group)" /> -->
                                    <input type="button" class="btn btn-outline-danger" value="Delete" (click)="deleteRow(i)" />
                                </td>
                            </tr>
                        </ng-container>
                    </tbody>
                </table>
                <ol *ngIf="submitted">
                    <li *ngFor="let group of getFormControls.controls; let i=index">
                        <ul>
                            <li *ngIf="((submitted || getFormControls.controls[i].get('firstname').touched) &&  getFormControls.controls[i].get('firstname').errors)">
                                <div *ngIf="((submitted || getFormControls.controls[i].get('firstname').touched) &&  getFormControls.controls[i].get('firstname').errors)" class="invalid-input">
                                    <div *ngIf="getFormControls.controls[i].get('firstname').errors.required">First Name is required</div>
                                    <div *ngIf="getFormControls.controls[i].get('firstname').errors.minlength">First Name must be at least 3 characters</div>
                                </div>
                            </li>
                            <li *ngIf="((submitted || getFormControls.controls[i].get('lastname').touched) &&  getFormControls.controls[i].get('lastname').errors)">
                                <div *ngIf="((submitted || getFormControls.controls[i].get('lastname').touched) &&  getFormControls.controls[i].get('lastname').errors)" class="invalid-input">
                                    <div *ngIf=" getFormControls.controls[i].get('lastname').errors.required">Last Name is required</div>
                                    <div *ngIf="getFormControls.controls[i].get('lastname').errors.minlength">Last Name must be at least 1 characters</div>
                                </div>
                            </li>
                            <li *ngIf="((submitted || getFormControls.controls[i].get('email').touched) &&  getFormControls.controls[i].get('email').errors)">
                                <div *ngIf="((submitted || getFormControls.controls[i].get('email').touched) &&  getFormControls.controls[i].get('email').errors)" class="invalid-input">
                                    <div *ngIf=" getFormControls.controls[i].get('email').errors.required">Email is required
                                    </div>
                                    <div *ngIf=" getFormControls.controls[i].get('email').errors.pattern">Enter Valid Email</div>
                                </div>
                            </li>
                            <li *ngIf="((submitted || getFormControls.controls[i].get('dob').touched) &&  getFormControls.controls[i].get('dob').errors)">
                                <div *ngIf="((submitted || getFormControls.controls[i].get('dob').touched) &&  getFormControls.controls[i].get('dob').errors)" class="invalid-input">
                                    <div *ngIf=" getFormControls.controls[i].get('dob').errors.required">Date of Birth is required</div>
                                </div>
                            </li>
                            <li *ngIf="((submitted || getFormControls.controls[i].get('mob').touched) &&  getFormControls.controls[i].get('mob').errors)">
                                <div *ngIf="((submitted || getFormControls.controls[i].get('mob').touched) &&  getFormControls.controls[i].get('mob').errors)" class="invalid-input">
                                    <div *ngIf=" getFormControls.controls[i].get('mob').errors.required">Mobile no is required</div>
                                    <div *ngIf=" getFormControls.controls[i].get('mob').errors.pattern">Enter Valid Mobile No</div>
                                </div>
                            </li>
                        </ul>
                    </li>
                </ol>
                <button type="submit" class="btn btn-outline-primary" [disabled]='!buttonstatus'>Submit</button>
            </form>
        </div>
    </div>
</div>
...