Form Builder with angular array

Asked

Viewed 5,245 times

3

I need to create a form that dynamically increments three fields by clicking a button.

I searched the angular site but there just shows how it does with a field.

I tried something like:

    <div formArrayName="variacoes">
      <div *ngFor="let variacao of variacoes.controls; let i=index">
        <label for="i">
          Nome Variação:
          <input [formControlName]="i" type="text" id="i" class="form-control">
        </label>

        <label for="i">
          Valor:
          <input [formControlName]="i" type="text" id="i" class="form-control">
        </label>

        <label for="i">
          SKU
          <input [formControlName]="i" type="text" id="i" class="form-control">
        </label>

      </div>
    </div>

productForm = this.fb.group({ variations: this.fb.array([ this.fb.control(''), ]) });

My duties:

get variacoes() {
    return this.produtoForm.get('variacoes') as FormArray;
  }

  addVariacao() {
    this.variacoes.push(this.fb.control(''));
  }

The idea would be that my form has an object called variacoes that inside it has arrays with key description, value and sku.

@Updating:

Not adding new fields as expected, updating existing fields:

      <div class="col-12 col-md-3">
        <button (click)="addVariacao()" type="button" class="btn btn-primary waves-effect"><i class="fa fa-plus-square create-icon"
            aria-hidden="true"></i>Adicionar variação</button>
      </div>

      <form [formGroup]="categoriaForm">
        <ng-container *ngFor="let item of variacoes.controls; let i = index;">
          <tr class="d-flex" [formGroup]="item">
            <td class="col-1 primary-color">{{i}}&nbsp;&nbsp;&nbsp; descricao</td>
            <td class="col-3"><input type="text" class="form-control" formControlName="descricao"></td>
              <td class="col-1 primary-color">{{i}}&nbsp;&nbsp;&nbsp; valor</td>
            <td class="col-3"><input type="text" class="form-control" formControlName="valor"></td>
            <td class="col-3"><input type="text" class="form-control" formControlName="sku"></td>
            <td class="col-1 primary-color">{{i}}&nbsp;&nbsp;&nbsp; Sku</td>
          </tr>
        </ng-container>
      </form>

  ngOnInit() {
    this.categoriaForm = this.fb.group({

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

    });

  get variacoes(): FormArray {
    return this.categoriaForm.get('variacoes') as FormArray;
  }

  addVariacao(){
    this.categoriaForm = this.fb.group({
      variacoes: this.fb.array([this.createFormGroup()])
    });;
  }

  createFormGroup() {
    return this.fb.group({
      descricao: [''],
      valor: [''],
      sku: ['']
    });
  }
  • https://answall.com/questions/327124/enviar-formul%C3%A1rio-angular/327190#327190

  • I did it these days ago

  • any doubt just talk

  • returned ERROR Error: formGroup expects a Formgroup instance. Please pass one in

  • public variacoes: any = [{Descricao : "descricao1", valor: "valor1", sku: 'sku1' }] categoriaForm: Formgroup;

  • and in the template: <form [formGroup]="categoriaForm">

  • Take a look at this my stackblitz I made in Willian’s reply

  • edited the question with update, if you can take a look...

  • then the following field is dynamic? comes from a db? if it is an add in the variacoes.Controls array that it will get dynamic with a push

  • I got it at home done... if I can’t get it over with as soon as I get there

  • if I am not mistaken and that Aki https://stackoverflow.com/questions/43934396/angular-4-patchvalue-based-on-index-in-formarray has even the remove

  • I tried: addVariacao(){ this.categoriaForm.patchValue({ variacoes: this.fb.array([this.createFormGroup()])

  • try this.variacoes.at(index). patchValue({Descricao:'test', value:1, sku:0}); index derived the position of the new array of this.variacoes. lenght and puts the value in place of the index ve if it works

Show 8 more comments

2 answers

2


  public formulario;

public ngOnInit() { this.formulario = new FormGroup({ data: new FormControl(), nome: new FormControl(), tipos: new FormBuilder().array([ new FormGroup({ id: new FormControl(), nome: new FormControl(), }), ]) }); }

  public adicionarForm() {
this.formulario.controls.tipos.controls.push(
  new FormGroup({
    id: new FormControl(),
    nome: new FormControl(),
  }),
);

}

2

Brother, whenever you try to add one more variation you end up replacing the whole content with just one:

addVariacao() {
    this.categoriaForm = this.fb.group({
        variacoes: this.fb.array([this.createFormGroup()])
});

Just add one more item in Formarray, like any array, using the function .push():

addVariacao() {
    this.variacoes.push(this.createFormGroup())
}

Here’s an example of code working, I hope I helped. xD

https://stackblitz.com/edit/simple-dynamic-form-builder-example?file=src/app/app.component.ts

Browser other questions tagged

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