简体   繁体   中英

Angular 2 | nested arrays in reactive form with dynamically built components

I'd like to build a reactive form in angular 2 and have the form component build dynamically. I've found some great tutorials on how to do this with simple forms:

https://toddmotto.com/angular-dynamic-components-forms

https://juristr.com/blog/2017/10/demystify-dynamic-angular-forms/

But I can't seem to figure out how to implement this when the data model contains an array of strings or objects. For example, consider an object of the following structure:

{
  'name': 'Big Name Hotel',
  'tags': [
    'clean',
    'cozy',
    'cheap'
  ],
  'locations': [
    {
      'city': 'Denver',
      'state': 'CO',
    },
    {
      'city': 'San Francisco',
      'state': 'CA',
    },
    {
      'city': 'Los Angeles',
      'state': 'CA',
    }
  ]
}

I can built a dynamic form component for the name element with one of the tutorials above, but how would I make it work with arrays of strings (tags) and arrays of objects (locations)?

=== EDIT FOR MORE CONTEXT ===

Here's the config data structure from one of the tutorials:

  config = [
    {
      type: 'input',
      label: 'Full name',
      name: 'name',
      placeholder: 'Enter your name',
    },
    {
      type: 'select',
      label: 'Favourite food',
      name: 'food',
      options: ['Pizza', 'Hot Dogs', 'Knakworstje', 'Coffee'],
      placeholder: 'Select an option',
    },
    {
      label: 'Submit',
      name: 'submit',
      type: 'button',
    },
  ];

What might the data structure look like for arrays of strings or arrays of objects?

I think (can't test right now) that you can just map the array into a FormArray .

const form = new FormGroup({
   tags : new FormArray(tags.map(tag => new FormControl(tag)))
});

Using FormBuilder ,

constructor(
    private fb: FormBuilder
  ) { }


  createForm() {
    ...

   this.form= this.fb.group({
         name: [this.data.name],
         ...
        locations: this.fb.array([])
   });

    const locationsFGs = this.data.locations.map(loc=> {
      return this.fb.group({
        city: [loc.city, Validators.required],
        state: [loc.state],
      });
    });
    const locationsFormArray: FormArray = this.fb.array(locationsFGs );
    this.form.setControl('locations', locationsFormArray);
  }

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