ОШИБКА Ошибка: не удается найти элемент управления с именем «1» в AngularJs - PullRequest
0 голосов
/ 05 мая 2020

Мне нужна твоя помощь. Я учу AngularJs. Я пытаюсь добавить новую строку динамически с помощью Nested FormArray в AngularJs. Я пишу код, и он работает нормально, но в нем есть ошибка. Когда я нажимаю кнопку «Добавить новую строку», для выполнения этой задачи требуется щелчок 4-5 раз. Когда я проверяю на консоли, он показывает следующие ошибки:

core.js:6185 ERROR Error: Cannot find control with name: '1'
    at _throwError (forms.js:3479)
    at setUpFormContainer (forms.js:3451)
    at FormGroupDirective.addFormGroup (forms.js:7581)
    at FormGroupName.ngOnInit (forms.js:6388)
    at callHook (core.js:4686)
    at callHooks (core.js:4650)
    at executeInitAndCheckHooks (core.js:4591)
    at refreshView (core.js:11814)
    at refreshDynamicEmbeddedViews (core.js:13154)
    at refreshView (core.js:11819)

    core.js:6185 ERROR Error: Cannot find control with path: '1 -> Name'
    at _throwError (forms.js:3479)
    at setUpControl (forms.js:3303)
    at FormGroupDirective.addControl (forms.js:7551)
    at FormControlName._setUpControl (forms.js:8367)
    at FormControlName.ngOnChanges (forms.js:8288)
    at FormControlName.wrapOnChangesHook_inPreviousChangesStorage (core.js:26853)
    at callHook (core.js:4690)
    at callHooks (core.js:4650)
    at executeInitAndCheckHooks (core.js:4591)
    at refreshView (core.js:11814)

мой. html код

<div class="col-12 col-sm-12 col-md-6 col-lg-6 col-xl-6 form-bg">
                <h2 class="mb-3">Add new row dynamically with Nested FormArray</h2>
                <form novalidate [formGroup]="FormGroup">
                <ng-container *ngIf='FormGroup.controls.itemRows!=null'>
                    <div *ngFor="let itemrow of FormGroup.controls.itemRows['controls']; let i=index;" [formGroupName]="i+1">
                        <div class="row">
                            <div class="col-12 col-md-2 form-group">
                                <input type="text" class="form-control" matInput placeholder="Name" formControlName="Name" >
                            </div>
                            <div class="col-12 col-md-2 form-group">
                                <input type="text" class="form-control" matInput placeholder="Roll No" formControlName="RollNo" >
                            </div>
                            <div class="col-12 col-md-2 form-group">
                                <input type="text" class="form-control" matInput placeholder="Class" formControlName="Class" >
                            </div>
                            <div class="col-12 col-md-2 form-group">
                                <input type="text" class="form-control" matInput placeholder="Mobile No" formControlName="MobileNo" >
                            </div>
                            <div class="col-12 col-md-2 form-group">
                             <button class="btn btn-danger" (click)="deleteRow(i)" >X</button>
                            </div>
                        </div>
                    </div>
                </ng-container>
                <div class="form-group pull-right">
                    <button class="btn btn-success" type="button" (click)="addNewRow()" [disabled]="FormGroup.invalid">
                        Add More
                    </button>
                </div>
            </form>
            </div>

, а мой .ts-код:

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

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


  FormGroup: FormGroup;
  TotalRow : number;

}

  constructor( private _fb: FormBuilder) { }

ngOnInit(): void {

this.FormGroup = this._fb.group({
     itemRows: this._fb.array([this.initItemRow()])
   });

  }


  initItemRow(){
    return this._fb.group({
     Name: [''],
     RollNo: [''],
     Class: [''],
     MobileNo: ['']
    });
  }

  addNewRow(){
    const control = <FormArray>this.FormGroup.controls['itemRows'];
    control.push(this.initItemRow());
  }

  deleteRow(index: number){
    const control = <FormArray>this.FormGroup.controls['itemRows'];
    if(control != null){
      this.TotalRow = control.value.length;
    }
    if(this.TotalRow > 1){
      control.removeAt(index);
    } else{
      alert ("One Record Mandatory");
      return false;
    }

  }
...