角度反应形式:无法通过路径找到控件:

时间:2018-02-05 15:32:25

标签: angular angular-reactive-forms

我有组件:cabinet-clinic-form.component.ts 在这里,我在诊所FormArray中遇到FormGroup验证问题。当我渲染页面时,我收到错误prntscr with error 我试图找到如何动态推送formGroups但仍然有错误。 按钮点击开始于AddClinic()事件,我添加了新的诊所。

这是我的代码:

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);
      }
    }

和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 个答案:

答案 0 :(得分:3)

[formGroupName]="clinicIndex + 1"更改为[formGroupName]="clinicIndex",索引1处无法控制

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

答案 1 :(得分:0)

[formGroupName]="clinicIndex"应该在下一个选择器层次结构中明智,例如 在下面。

<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>