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>