How can I define an array inside my formgroup?

0

I have the following function that creates a form group:

My ngOnInit:

ngOnInit() {

    //Ao iniciar a tela deve carregar o formgroup padrão das variações
    this.variacaoForm = this.fb.group({

      variacoes: this.fb.array([this.createFormGroup()])

    });


 createFormGroup(): FormGroup {
    return this.fb.group({
      atributo: "",
      preco: null,
      listaatributos: [{}],
      sku: '',
      tipo: '',
      id: '',
      id_produto: '',
      estoque_variacao: 0,
      linkfotovariacao: '',
      created_at: '',
      foto_prin_1: '',
      foto_prin_2: '',
      foto_prin_3: '',
      foto_prin_4: '',
      foto_prin_5: '',
      foto_prin_6: ''
    });
  }
}

In this list, attributes need to be an array so I can put several values. I tried to add in a function these data that I need to keep in this list attributes:

   adicionaAtributo(index: number){

   this.variacaoForm.value.variacoes[index].listaatributos.push(this.idAtributo);
  }

In case I would like to add in my form variation in the position informed by the parameter that attribute id. But when this function is triggered, it is returned:

  

ERROR TypeError: Can not read property 'list attributes' of undefined

My idea is that I need reactive forms, I'm in a scenario where I can have more than one variation, and in each variation can have N attributes.

The structure I need to send to the backend would look like this:

variações: [{"estoque_variacao": 900, "atributos":[12,13]}]

Where in this key attributes I tried to add through the function:

adicionaAtributo(index: number){}
    
asked by anonymous 07.11.2018 / 19:22

1 answer

2

I created a Stackblitz that I tried to simulate your example.

I've created a list that will add and / or remove items from your listaatributos , looks like this:

 add(index: number, newValue) {
   this.listAtributos.push(newValue); // lista de number[]
   const control = (<FormArray>this.form.controls['variacoes']).at(index);
   control.patchValue({ listaatributos: this.listAtributos});
 }
    
07.11.2018 / 20:24