形成 Angular 数组

问题描述 投票:0回答:2

我很难将此表单与 html 集成。你能帮助我吗?我尝试了一些方法,但无法连接,因为我使用的是 FormArray。 我制作了表单,但访问 html 中的控件非常复杂。 我需要它是数组形式,因为这将有几个带有类别的数组。 我需要它是数组形式,因为这将有几个带有类别的数组。

Form in Component TS

  testeForm: FormGroup = this.fb.group({
    feedstock: this.fb.array([
      this.addFeedStockArray()
    ])
  });
  
  
    addFeedStockArray(): FormGroup {
    return this.fb.group({
      category: "",
      position: "",
      feedstockOptions: this.fb.array([
        this.addFeedStockOptions()
      ]),
   })
 }
  
  
    addFeedStockOptions(): FormGroup {
     return this.fb.group({
      name: '',
      code: '',
      price: {
        amount: '',
        currency: ['BRL'],
      }
    })
  }
  
  
  addfeedStockClick(): void {
    (<FormArray>this.testeForm.get('feedstock')).push(this.addFeedStockOptions());
  }
              <div [formGroup]="testeForm" style="margin-left: 40px">
                <div class="second-column row" formArrayName="feedstock" >
                  <div class="row" [formGroupName]="i" *ngFor="let feedstock of feedstock.get('feedstockOptions')?.controls; let i = index">
                    <div class="form-group col">
                        <label>
                          NOME:
                        </label>
                        <input class="form-control"
                              placeholder="--" formControlName="name" >
                    </div>
                    <div class="form-group col">
                        <label>
                          CÓDIGO:
                        </label>
                        <input class="form-control"
                              placeholder="--" formControlName="code">
                    </div>
                    <div class="form-group col">
                        <label>
                          PREÇO:
                        </label>
                        <input class="form-control"
                              currencyMask
                              [options]="{ prefix: 'R$ ', thousands: '.', decimal: ',', align:'left'}"
                              min="0"
                              placeholder="R$" formControlName="price" >
                    </div>
                    <div class="form-group col">
                      <i class="material-icons close-category"  style="margin-top: 40px" (click)="removefeedStockClick(i)" >
                        close
                      </i>
                    </div>
                  </div>
                </div>
              </div>

angular typescript forms
2个回答
1
投票

我建议进行最小的更改,看看是否可以解决您的问题

<div [formGroup]="testeForm" style="margin-left: 40px">
  <div class="second-column row" formArrayName="feedstock" >
    <ng-container *ngFor="let feedstock of feedstock.get('feedstockOptions')?.controls; let i = index">
      <div class="row" [formGroupName]="i">
        <div class="form-group col">
          <label>NOME:</label>
          <input class="form-control" placeholder="--" formControlName="name" >
         </div>
      </div>
      ......
    </ng-container>

使用 ng-container 来包装 *ngFor 指令

更新

看到完整代码后,发现有一个较大的错误: FormArray 有 2 层,需要这样访问。

<div [formGroup]="testeForm" style="margin-left: 40px">
  <div class="second-column row" formArrayName="feedstock" >
    <ng-container *ngFor="let fcFeedStock of testeForm.get('feedstock')?.controls; let i = index">
      <ng-container [formGroupName]="i">
        <ng-container formArrayName="feedstockOptions">
          <ng-container *ngFor="let feedstockOption of fcFeedStock.get('feedstockOptions')?.controls; let j = index">
            <div class="row" [formGroupName]="j">
              <div class="form-group col">
                <label>NOME:</label>
                <input class="form-control" placeholder="--" formControlName="name" >
              </div>
            </div>
        ......
        </ng-container>
    </ng-container>
  </ng-container>
</div>

更新2:

显示价格 > 金额

价格是一个 FormGroup,金额是一个 FormControl:

 ...
 <div class="row" [formGroupName]="i">
    <div class="form-group col">
      <label>NOME:</label>
      <input class="form-control" placeholder="--" formControlName="name" >
     </div>
     <div formGroupName="price">
       <input formControlName="amount">
     </div>
  </div>
  ...

如何向数组添加一个新元素:

问题是您混淆了 2 个 FormArrays“feedstock”和“feedstockOptions”。

// This function should do feedstock.push(this.addFeedStockArray())
addfeedStockClick(): void {
  (<FormArray>this.testForm.get('feedstock')).push(this.addFeedStockArray());
}

要添加到 feedstockOptions,您首先需要 feedstock 的索引,访问它的 feedstockOptions,然后推送到它:

(<FormArray>(<FormArray>this.testForm.get('feedstock')).at(index).get('feedstockOptions')).push(this.addFeedStockOptions());

或者如果您可以直接访问 fcFeedstock,则代码行将简化为:

(<FormArray>fcFeedstock.get('feedstockOptions')).push(this.addFeedStockOptions())

0
投票

首先您需要声明其中包含表单数组的表单组

public uploadformGroup = this._fb.group({ products: new FormArray([], [Validators.required], []), });

从表单组中获取特定数组作为表单数组

 get arrayformControls() { return (this.uploadformGroup.get('products') as FormArray).controls; };

然后循环运行,将每个表单组插入到表单数组中

this._api.getProducts().subscribe({
  next: (res) => {
    this.results = res;
    this.results.forEach((ob,i) => {
      this.arrayformControls.push(
          new FormGroup({
          productName: new FormControl(ob.productName, [Validators.required, Validators.minLength(5)]),
        })
      );
    });
    console.log('this.arrayformControls',this.arrayformControls);
    console.log('this.arrayformControls',this.uploadformGroup);


  },
  error: (err) => {},
  complete: () => {
    this.uploadformGroup.value.products = this.arrayformControls
  },
});

html 看起来像这样

<form
  [formGroup]="profileFormArray"
  (ngSubmit)="checkArrayOfProductsInForm($event)"
>
  <div formArrayName="productsForm">
    <button type="submit" [disabled]="!productsForm.valid">
      Submit changes and assign from form to products array
    </button>
    <div *ngFor="let p of productsForm.controls; let i = index">
      <!-- The repeated alias template -->
      <div>Id:{{ this.products[i].id }}</div>
      <div>Name:{{ this.products[i].productName }}</div>
      <input
        type="text"
        [formControlName]="i"
        (keyup)="changeIndexOfProduct(i)"
      />
    </div>
  </div>
</form>
© www.soinside.com 2019 - 2024. All rights reserved.