Home > Back-end >  dynamic angular form builder according to array
dynamic angular form builder according to array

Time:08-31

i have array and want to set formControl from it.

How to create dynamic formControl?

const myArr = [ { "name": [ "Ivan" ] }, { "surname": [ "avan" ] } ]
form!: FormGroup;

constructor(private fb: FormBuilder){
this.form = this.fb.group(
  this.e.map(i => {
    return { [i.name]: [i.surname] }
  }));
}

This code return undefined form, so how to solve it? thanks

CodePudding user response:

You need to use a FormArray. However, your data looks a bit off to me. I'm assuming you have an array of objects as such:

  [
    {
      "name": "Ivan",
      "surname": "Avan"
    },
    ...
  ]

Making your component:

export YourComponent implements OnInit {

  data: { name: string, surname: string } = [{
      name: 'Ivan',
      surname: 'Avan',
    }];
  form: FormGroup;

  ngOnInit(): void {
    this.form = new FormGroup({
      name: new FormArray(this.data.map(obj => {
        return new FormGroup({
          name: new FormControl(obj.name),
          surname: new FormControl(obj.surname),
        });
      }) || []);
    });
  }

}

  • Related