Angular 5 build form array from JSON result

I am having the following issue with Angular form arrays, I was wondering if someone could help me out as I am quite new with Angular?

Apologies I cannot provide a plunker due to the complexity of the project (lots of dependencies and complex code), but I will do my best to provide as much detail as I can!

I have a JSON response from a service call that contains a group of fields (called "myFields") such as:

0:
name: "field1"
1:
name: "field2"

I am getting this response from a call to an API, and I need to build a form using the fields from the reponse. I am currently looping through this response and attempting to build a form array as follows:

constructor(private formBuilder: FormBuilder){

    this.myFormGroup = this.formBuilder.group({
        aliases: this.formBuilder.array([
        ])
    });

}

get aliases() {
    return this.myFormGroup.get('aliases') as FormArray;
}

getServiceFields(){

    *call to get fields and store in "myFields"*
    for (let item of myFields) {
        this.aliases.push(this.createGroup(item));
    }
}

createGroup(item): FormGroup {
    return this.formBuilder.group({
        name: new FormControl(item.name)
    });
}

And in my view I have:

<div [formGroup]="myFormGroup" class="example-form">
    <div formArrayName="aliases" >
    <div *ngFor="let field of myFormGroup.controls.aliases.controls; 
    let i=index">

        <mat-form-field>
            <input matInput placeholder="{{field.value.name}}"
            formControlName="{{field.value.name"}}>
        </mat-form-field>

The issue I am having is that nothing shows on the page and this is the error I see in the console window:

Error: Cannot find control with path: 'aliases -> name'

I will also attach a screenshot showing the structure of my FormGroup in the console window:

FormGroup structure

Hopefully this is enough information, if additional details are required I can provide them. Anyone have an idea where I am going wrong? Thanks!

Edit: I cannot hard code the formControlName (e.g formControlName="name") as I am looping through the list of controls in "aliases", this is why I am trying to use {{field.value.name}}

1 answer

  • answered 2018-10-22 14:50 Ajay Ojha

      <div *ngFor="let field of myFormGroup.controls.aliases.controls; 
        let i=index">
    <div [formGroup]="field">
            <mat-form-field>
                <input matInput placeholder="{{field.value.name}}"
                formControlName="name">
            </mat-form-field>
            </div>
    

    replace above code in your html.

    Problem is you are not binding formgroup before formcontrolname. formcontrolname should work under formgroup.

    Please let me know if you have any question.