Replication structure to insert data into a form group

-1

I have the following form group:

 this.variacaoForm = this.fb.group({

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

 });

  createFormGroup(): FormGroup {
    return this.fb.group({
      valor: '',
      preco: null,
      sku: '',
      tipo: '',
      id: '',
      id_produto: '',
      created_at: ''
    });
  }

My template:

<form *ngIf="mostraVariacoes" [formGroup]="variacaoForm">
        <ng-container *ngFor="let item of variacoes.controls; let i = index;">
          <div class="container-fluid" [formGroup]="item">

At one point in my application I get the data backend and I need to insert them into the form group I created.

I tried something like:

for(let i=0;i<this.produto.variacao.length;i++){
  (<FormControl>this.variacaoForm.value['variacoes'])
  .setValue(this.produto.variacao[i], { onlySelf: true });
}

But I get:

  

this.variacaoForm.value.variacoes.setValue is not a function

I've also tried:

for (let i = 0; ithis.variacaoForm.controls ['variacoes'])   .setValue (this.product.variance [i], {onlySelf: true}); }

So I get:

  

ERROR Error: Must supply a value for form control at index: 0.

    
asked by anonymous 24.09.2018 / 13:50

1 answer

0

I was able to resolve it as follows:

for(let i=0;i<this.produto.variacao.length;i++){
  this.variacoes.push(this.createFormGroup(produto,i));
}

  createFormGroup(produto?: any, indice?: number): FormGroup {
    if(produto){
      return this.fb.group({
        valor: produto.variacao[indice].valor,
        preco: produto.variacao[indice].preco,
        sku: produto.variacao[indice].sku,
        tipo: produto.variacao[indice].tipo,
        id: '',
        id_produto: '',
        created_at: ''
      });
    }else{
    return this.fb.group({
      valor: '',
      preco: null,
      sku: '',
      tipo: '',
      id: '',
      id_produto: '',
      created_at: ''
    });
  }
}
    
24.09.2018 / 15:46