5
votes

I am getting an error from my component, TypeError: control.setParent is not a function. Using FormBuilder, I build a FormArray and initiate the form group in constructor. So this error as I understand it, is saying that a form control has not been set yet. Not sure that makes sense to me

Here is the component so far...

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, FormArray } from '@angular/forms';
import { Observable } from 'rxjs/Observable';
import { tap, map } from 'rxjs/operators';
import { MediaListService } from '../../services/media-list.service';
import { ActivatedRoute } from '@angular/router';

@Component({
    selector: 'app-media-list-builder',
    templateUrl: './media-list-builder.component.html'
})
export class MediaListBuilderComponent implements OnInit {

    mediaListForm: FormGroup;
    contactsDataSource$: Observable<any>;
    mediaListDataSource$: Observable<any>;
    mediaListId: number;
    mediaList: any;
    searchText = '';
    searchKey = 'name';
    tableView = true;

    constructor(
        private fb: FormBuilder,
        private router: ActivatedRoute,
        private medialistsrv: MediaListService
    ) {

        this.mediaListForm = this.fb.group({
            contacts: this.fb.array([])
        });

        this.router.params.subscribe(params => {
            this.mediaListId = +params['id'];
        });
    }

    get _contacts(): FormArray {
        return this.mediaListForm.get('contacts') as FormArray;
    }

    ngOnInit() {

        this.medialistsrv.getMediaListById(this.mediaListId).subscribe(
            response => {
                this.mediaList = response.contacts;
                this.mediaList = this.mediaList.map(obj => obj.contactId);
                this.mediaList.forEach(id => {
                    this._contacts.push(id);
                });
            }
        );

        this.contactsDataSource$ = this.medialistsrv.getAllContacts()
            .map(response => response);

    }

    toggleView(arg) {
        this.tableView = arg;
    }

}
1
I believe you need to import ReactiveFormsModulerrd
yes I have that alreadySandra Willford
@SandraWillford did you find an answer to this? If yes, perhaps you can post an answer here: stackoverflow.com/questions/51209125/…R. Richards

1 Answers

0
votes

Let's Consider one solution it's work fine for me.

 this.customerFormGroup= this.formBuilder.group({
      firstName: ['', Validators.required],
      lastName:['', Validators.required],
      customerAddressDTOList:this.formBuilder.array([])
    });

then

get customerAddressDTOList() {
    return <FormArray>this.customerFormGroup.controls['customerAddressDTOList'];
  }

after this performed push operation

addCustomer(){
 this.customerAddressDTOList.push(this.formBuilder.control(anyvalue));
}