Angular 2 Form Error : path.split is not a function at <FormArray>this.myForm.get(i)

UzUmAkI_NaRuTo picture UzUmAkI_NaRuTo · Nov 26, 2016 · Viewed 8.4k times · Source

Trying to make a nested dynamic form in Angular 2.

Form Skeleton

this.myForm= this.formBuilder.group({
        programmes: this.formBuilder.array([this.initProgramme(),]),
    });

initProgramme() {
        return this.formBuilder.group({
            tickets: this.formBuilder.array([this.initTicket(),])
        });
    }


initTicket() {
        return this.formBuilder.group({
            field1:''
        });
    }


Adding programme dynamically works with following function :-

addProgToForm(){

    const control = <FormArray>this.myForm.get('programmes');
        control.push(this.initProgramme());
  }


adding ticket to programme THROWS ERROR

addTicket(programme: any) {
        const control = (<FormArray>this.myForm.get('programmes')).get(programme); // THROWS ERROR  HERE
         (<FormArray>control.get('tickets')).push(this.initTicket());
    }


At .get(programme) it says path.split is not a function


PS - programme in 'get(programme)' is the index of Programme Form Array to which dynamic tickets are to be added. It is retrieved correctly from *ngFor . Example :- index 0 for first programme added.

Answer

Sergii HRappka picture Sergii HRappka · Jun 30, 2017

Try to get control by string index: .get(programme.toString())

addTicket(programme: any) {
    const control = (<FormArray>this.myForm.get('programmes')).get(programme.toString());
     (<FormArray>control.get('tickets')).push(this.initTicket());
}