Repeat structure to insert data into a form group

Asked

Viewed 78 times

-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 a time of my application I receive from the backend the data and need to insert them in this form group that 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 also tried to:

for(Let i=0;ithis.variacaoForm.Controls['variacoes']) . setValue(this.producto.variacao[i], { onlySelf: true }); }

So I get:

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

  • try that code if it works I put as an answer

  • It didn’t work, I believe I should add calling my function: this.variacaForm = this.fb.group({ variables: this.fb.array([this.createFormGroup(product)]) });

1 answer

0


I was able to solve it this way:

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: ''
    });
  }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.