angular 5 установить значение для вложенного массива формы группы форм

мой объект продукта, содержащий массив, готов на стороне клиента следующим образом:

 public product =>>    require: [{ id: 397, product_id: 51, item: "asdasdd" },{ id: 398, product_id: 51, item: "bbbbbb" }]

для редактирования существующих данных я хочу добавить элемент в мой ввод формы при инициализации формы (я должен вводить данные для каждого элемента)

как добавить мой элемент к этому... я написал цикл for, чтобы добавить элемент в форму, которую вы можете видеть ниже, но это не работает

это моя форма:

  public product;
  public requirementForm: FormGroup;

  constructor(private _store: StoreService, private fb: FormBuilder) {
    this.createForm();

  }

  createForm() {
    this.requirementForm = this.fb.group({
      itemRows: this.fb.array([])
    });
    this.requirementForm.setControl('itemRows', this.fb.array([]));
  }

  ngOnInit() {

    this.requirementForm.setControl('itemRows', this.fb.array([]));
    this.requirementForm = this.fb.group({
      itemRows: this.fb.array([this.initItemRows()])
    });


    this._store.ownersingleView(this.pid).subscribe((data: any) => {
      this.product = data;

      **for (let i = 0; i < data.require.length; i++) {
        const control = <FormArray>this.requirementForm.controls['itemRows'];
        control.push(this.initItemRows());
        this.requirementForm.controls['itemRows'].controls['itemname'].setValue(this.product.require[i].item, {onlySelf: true});
      }**

    })

  }

  initItemRows() {
    return this.fb.group({
      itemname: ['']
    });
  }

  addNewRow() {
    const control = <FormArray>this.requirementForm.controls['itemRows'];
    control.push(this.initItemRows());
  }

HTML-форма:

<div class="row">
  <div class="col s12 m12 l12">
    <form [formGroup]="requirementForm">
      <div formArrayName="itemRows">
        <div class="item_x">
          <div [@itemAnim]="true" class="item_in"
               *ngFor="let itemrow of requirementForm.controls.itemRows.controls; let i=index"
               [formGroupName]="i">
            <div class="i-in">
              <div class="requirement_item">
                <h6>نیازمندی #{{ i + 1 }}</h6>
                <div class="form-group">
                  <label>نام آیتم</label>
                  <input formControlName="itemname" class="form-control">
                </div>
              </div>
              <div class="requirement_x">
                <div class="requirment_del">
                  <div class="rdc">
                    <button *ngIf="requirementForm.controls.itemRows.controls.length > 1" (click)="deleteRow(i)"
                            mat-mini-fab=""><i class="mdi mdi-delete"></i>
                    </button>
                  </div>

                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="action">
        <div class="action_i">
          <div class="ac_in">
            <button mat-mini-fab color="primary" (click)="addNewRow()"><i class="mdi mdi-plus"></i></button>
          </div>
        </div>
      </div>
    </form>
  </div>
</div>

person devmrh    schedule 17.05.2018    source источник


Ответы (1)


я открываю stackblitz, вы можете попробовать что-то вроде этого:

product.component.ts:

import { Component, Input} from '@angular/core';
import {FormGroup} from "@angular/forms";


@Component({
  selector: 'product',
  templateUrl: './product.component.html'
})
export class ProductComponent {
  @Input('group')
  public productForm: FormGroup;
}

product.component.html:

<div [formGroup]="productForm">
  <div class="form-group col-xs-6">
    <label>id</label>
    <input type="text" class="form-control" formControlName="id">
    <small [hidden]="productForm.controls.id.valid" class="text-danger">
      id is required
    </small>
  </div>
  <div class="form-group col-xs-6">
    <label>productId</label>
    <input type="text" class="form-control" formControlName="productId">
  </div>
  <div class="form-group col-xs-6">
    <label>item</label>
    <input type="text" class="form-control" formControlName="item">
  </div>
</div>

app.component.ts:

import { Component} from '@angular/core';
import {FormArray, FormBuilder, FormGroup, Validators} from "@angular/forms";


@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})
export class AppComponent {

  public myForm: FormGroup;

  constructor(private _fb: FormBuilder) { }

  ngOnInit() {
    this.myForm = this._fb.group({
      name: ['', [Validators.required, Validators.minLength(5)]],
      products: this._fb.array([])
    });

    this.addProduct();
  }

  initProduct() {
    return this._fb.group({
      id: ['', Validators.required],
      productId: [''],
      item: ['']
    });
  }

  addProduct() {
    const control = <FormArray>this.myForm.controls['products'];
    const productCtrl = this.initProduct();
    control.push(productCtrl);
  }

  removeProduct(i: number) {
    const control = <FormArray>this.myForm.controls['products'];
    control.removeAt(i);
  }

  save(model: Product) {
    console.log(model);
  }
}

export interface Products {
  name: string;
  products: Product[];
}

export interface Product {
  id: string;
  productIid: string;
  item:string;
}

app.component.html:

<div class="container">
  <div class="row">
    <div class="col-md-12">
      <div class="margin-20">
        <h4>Add Product</h4>
      </div>
      <form [formGroup]="myForm" novalidate (ngSubmit)="save(myForm)">
        <div class="form-group">
          <label>Name</label>
          <input type="text" class="form-control" formControlName="name">
          <small *ngIf="!myForm.controls.name.valid" class="text-danger">
            Name is required (minimum 5 characters).
          </small>
        </div>

        <div formArrayName="products">
          <div *ngFor="let product of myForm.controls.products.controls; let i=index" class="panel panel-default">
            <div class="panel-heading">
              <span>Product {{i + 1}}</span>
              <span class="glyphicon glyphicon-remove pull-right" *ngIf="myForm.controls.products.controls.length > 1" (click)="removeProduct(i)">remove</span>
            </div>
            <div class="panel-body" [formGroupName]="i">
              <product [group]="myForm.controls.products.controls[i]"></product>
            </div>
          </div>
        </div>

        <div class="margin-20">
          <a (click)="addProduct()" style="cursor: default">
            Add another product +
          </a>
        </div>

        <div class="margin-20">
          <button type="submit" class="btn btn-primary pull-right" [disabled]="!myForm.valid">Submit</button>
        </div>
        <div class="clearfix"></div>

        <div class="margin-20">
          <div>myForm details:-</div>
          <pre>Is myForm valid?: <br>{{myForm.valid | json}}</pre>
          <pre>form value: <br>{{myForm.value | json}}</pre>
        </div>
      </form>
    </div>
  </div>
</div>

и, наконец, app.module.ts:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import { ProductComponent} from "./product.component";
import { ReactiveFormsModule , FormsModule } from "@angular/forms";


@NgModule({
  declarations: [
    AppComponent,
    ProductComponent,

  ],
  imports: [
    BrowserModule,
    ReactiveFormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

надеюсь это поможет.

person Fateme Fazli    schedule 17.05.2018