简体   繁体   中英

Angular 2 Forms Nested Ojects in Arrays

I am trying to figure out nested objects in arrays in forms for angular. I have read several questions and posts but am still not able to figure it out. Maybe I am just missing something very simple.

See below simplified code.

HTML

 <form [formGroup]="userForm" (ngSubmit)="submit(userForm.value)">
    <hr>
    <div formGroupName="type">
        <div formArrayName="options">
            <div *ngFor="let child of userForm.controls.type.controls.options.controls; let i = index" >
                <div formGroupName="{{i}}">
                    <label>{{i+1}}. Test: </label>
                    <input formControlName="test" /><br>
                    <label>{{i+1}}. Label: </label>
                    <input formControlName="label" /><br>
                    <label>{{i+1}}. Value: </label>
                    <input formControlName="value" />
                </div>
            </div>
        </div>
    </div>
    <button type="submit">Submit</button>
</form>
<br>
<pre>{{userForm.value | json }}</pre>

Application

export class App {
    name:string;
    userForm: FormGroup;
    fields: any;

    ngOnInit() {
    this.fields = {
      isRequired: true,
      type: {
        options: [
          {
            test {
              name: 'test1'
            }
            label: 'Option 1',
            value: '1',
          },
          {
            test {
              name: 'test2'
            }
            label: 'Option 2',
            value: '2'
          }
        ]
      }
    };
    this.userForm = this.fb.group({
      type: this.fb.group({
        options: this.fb.array([])   
      })
    });
    this.patch()
  }

  submit(value) {
    console.log(value);
  }

  constructor(private fb: FormBuilder) {  }

  patch() {
    const control = <FormArray>this.userForm.controls.type.controls['options'];
    this.fields.type.options.forEach(x => {
      control.push(this.patchValues(x.label, x.value))
    })
  }

  patchValues(label, value) {
    return this.fb.group({
      test: {name: "HELP"},
      label: [label],
      value: [value]
    })    
  }

}

My output looks like this...

1. Test: [object Object]
1. Label: Option 1
1. Value: 1
2. Test: [object Object]
2. Label: Option 2
2. Value: 2

   [Submit]

and the data object is

{
  "type": {
    "options": [
      {
        "test": {
          "name": "HELP"
        },
        "label": "Option 1",
        "value": "1"
      },
      {
        "test": {
          "name": "HELP"
        },
        "label": "Option 2",
        "value": "2"
      }
    ]
  }
}

I am looking to change the html template to display test.name instead of the test object. Am I initializing the form correctly or am I calling the field incorrectly from the html code? When I change formControlName="test" to formControlName="test.name" it errors out stating that test.name does not exist.

Desired output...

1. Test: HELP
1. Label: Option 1
1. Value: 1
2. Test: HELP
2. Label: Option 2
2. Value: 2

In your code you need to change the following:

patchValues(label, value) {
    return this.fb.group({
      **test: {name: "HELP"},**
      label: [label],
      value: [value]
    })    
  }

All the names on the left hand side are the formControlNames. That's why you get an error when you try to use test.name because it does't exist as a formControlName.

I think what you are trying to achieve is something similar to Dynamic forms. Please refer to the following link as it would help in the implementation: https://angular.io/guide/dynamic-form

If you need to maintain the build of your original data, you need to nest your test as a nested formgroup inside your formgroup, so it could look like this:

this.fields.type.options.forEach(x => {
  control.push(this.patchValues(x))
})

patchValues(x) {
  return this.fb.group({
    // nested group!
    test: this.fb.group({
      name: [x.test.name]
    }),
    label: [x.label],
    value: [x.value]
  })
}

and template would look like this:

<div formGroupName="{{i}}">
  <div formGroupName="test">
    <label>{{i+1}}. Test: </label>
    <input formControlName="name" /><br>           
  </div>
  <label>{{i+1}}. Label: </label>
    <input formControlName="label" /><br>
    <label>{{i+1}}. Value: </label>
    <input formControlName="value" />
  </div>

DEMO

If it does not need to be maintained, you can of course just extract the name from the test instead like so:

control.push(this.patchValues(x.label, x.value, x.test.name))

patchValues(label, value, name) {
  return this.fb.group({
    test: [name],
    label: [label],
    value: [value]
  })    
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM