3
votes

I have component: cabinet-clinic-form.component.ts And here I have problem with FormGroup validation in clinics FormArray. When I render page I get error prntscr with error I tried to find how to dynamically push formGroups but still have error. On button click begins onAddClinic() event and I add new clinic.

Here is my code:

export class CabinetClinicFormComponent implements OnInit {
      doctorForm: FormGroup;
      ngOnInit() {
        this.doctorForm = new FormGroup({
          'clinics': new FormArray([]),
        });
      }
      onAddClinic() {
        const newClinic = new FormGroup({
            'city' : new FormControl(null),
            'clinicname' : new FormControl(null),
        });
        (<FormArray>this.doctorForm.get('clinics')).push(newClinic);
      }
      onSubmit() {
        console.log(this.doctorForm);
      }
    }

and cabinet-clinic-form.component.html

<div
      class="clinic-group"
      formArrayName="clinics"
    >
      <div
        *ngFor="let clinicControl of doctorForm.get('clinics').controls; let clinicIndex = index;"
        [formGroupName]="clinicIndex"
      >
        <div class="clinic-group__title">Клиника #{{clinicIndex + 1}}</div>
        <div class="form-group">
          <label
            [attr.for]="'city' + clinicIndex + 1"
            class="control--label"
          >
            <span class="control--label-text">Город</span>
          </label>
          <input
            type="text"
            [attr.id]="'city' + clinicIndex + 1"
            [formControlName]="city"
            class="form-control"
          >
        </div>
        <div class="form-group">
          <label
            [attr.for]="'clinicname' + (clinicIndex + 1)"
            class="control--label"
          >
            <span class="control--label-text">Название клиники</span>
          </label>
          <input
            type="text"
            [attr.id]="'clinicname' + (clinicIndex + 1)"
            [formControlName]="clinicname"
            class="form-control"
          >
        </div>
      </div>
    </div>

    <button type="button" (click)="onAddClinic()">Добавить клинику</button>
2
Finally I found my mistake. 8 hours searching and the problem was [formControlName]="clinicname" but need to use formControlName="clinicname". That's it. - sanchahous
you saved my life thanks - Seungwon

2 Answers

3
votes

change the [formGroupName]="clinicIndex + 1" to [formGroupName]="clinicIndex" there is no control at index 1

  <div
        *ngFor="let clinicControl of doctorForm.get('clinics').controls; let clinicIndex = index;"
        [formGroupName]="clinicIndex"
      >
0
votes

[formGroupName]="clinicIndex" should be in next selector hierarchy wise, like below.

<div *ngFor="let clinicControl of doctorForm.get('clinics').controls; let clinicIndex = index;">
    <div [formGroupName]="clinicIndex">
    <div class="clinic-group__title">Клиника #{{clinicIndex + 1}}</div>
...
</div>
<div>