嵌套反应形式Angular 5的可观察物

时间:2018-07-03 06:46:19

标签: angular observable angular-reactive-forms

我有这样的反应形式:

<form *ngIf="people$ | async;" [formGroup]="applicationForm" (ngSubmit)="submitForm()">

  <person-form
    [parentForm]="applicationForm"
    (added)="addPerson()"
    (removed)="removePerson($event)">
  </person-form>

  <button type="submit">Submit</button>

</form>

以及适当的课程

export class FormComponent implements OnInit {
  applicationForm: FormGroup;
  people$: Observable<any>;

  constructor( public peopleService: PeopleService ) {}

  ngOnInit() {
    this.applicationForm = this.fb.group({});

    this.people$ = this.peopleService.getPeopleData().pipe(
      tap(peopleData => {
        this.applicationForm.setControl('people', this.fb.array(peopleData || []));
      })
    );
  }
}

我是ngOnInit,我从服务中获取数据,这给了我很多人,并推向applicationForm作为表单控件。当我将该applicationForm传递给数组中的嵌套表单时,会发生问题: 这是嵌套表单的模板:

<div [formGroup]="parentForm">
  <div formArrayName="people">
    <div *ngFor="let item of people; let i = index;">
      <div [formGroupName]="i">
        <input type="number" formControlName="age" />
      </div>
    </div>
  </div>
</div>

和一类嵌套表单

export class BorrowerFormComponent {
  @Input() parentForm: FormGroup;
  @Output() added: EventEmitter<any> = new EventEmitter<any>();
  @Output() removed: EventEmitter<any> = new EventEmitter<any>();
  onAdd() {
    this.added.emit();
  }

  onRemove(index) {
    this.removed.emit(index);
  }

  get people() {
    return (this.parentForm.get('people') as FormArray).controls;
  }
}

我还会发出一些添加和删除数组元素的内容,因此我省略了这些内容以使代码更短 所以我会在很长一段时间后向我显示控制权,但是我也有错误:

Cannot find control with path: 'people -> 0 -> age'

我错过了什么吗?为什么找不到“人-> 0->年龄”? 此“年龄”字段从服务中返回。

1 个答案:

答案 0 :(得分:0)

您没有在formControl中声明“年龄”

ngOnInit(){

    initGroup() {
        let rows = this.parentForm.get('people') as FormArray;
        rows.push(this.fb.group({
          age: [null, Validators.required],
        }))   
     } 
}