使用* ngFor的Angular2奇怪的表单行为

时间:2017-01-19 09:33:53

标签: arrays angular angular2-forms

嘿,对于那些用瓶子看过我关于这个表格的几篇文章的人再次嘿...它又回来了。

在我开始解释任何内容之前,这里有一个工作的plunkr ,显示了这个问题:

Working Plunkr

N.B:我在第二个阵列中显示了瓶子typeId,它清楚地显示了问题。

问题:

当我遇到以下情况的问题时,我正在检查绑定以确保我选择的值正确传递:

  • 1:添加一些OrderReturn order,以便您有多个输入。
  • 2:选择一些类型并在这些输入中设置一些值。
  • 3:如果删除任何不是最后一个数组的输入,然后重新添加一个输入,即使绑定到ngModel仍然正确,这些值也会混乱。

有没有办法使用标准Template Driven Forms来避免这种奇怪的行为?或者我必须通过ReactiveForms

我会在这里解释我的大部分代码:

我正在向我的表单bottleArray发送包含nametypeId的气瓶(@Input())数组。

我将此数组及其对象深度克隆为两个独立的数组:orderedClonedArrayBottlesreturnedClonedArrayBottles

然后我将值添加到相应的显示数组:orderedBottlesreturnedBottles,其值现在为count

...
@Input() private bottleArray: Bottle[];

private orderedClonedArrayBottles: Bottle[] = [];
private returnedClonedArrayBottles: Bottle[] = [];
private orderedBottles: BottleCommand[] = [];
private returnedBottles: BottleCommand[] = [];

ngOnChanges(changes) {
  // Get @Input data when it's ready
  if (changes.bottleArray) {
    // Cloning the Array AND the Bottles
    this.orderedClonedArrayBottles = this.deepClone(changes.bottleArray.currentValue);
    this.returnedClonedArrayBottles = this.deepClone(changes.bottleArray.currentValue);

    // Display first rows
    if (this.orderedClonedArrayBottles.length > 0) {
      this.orderedBottles.push(this.orderedClonedArrayBottles[0]);
    }
    if (this.returnedClonedArrayBottles.length > 0) {
      this.returnedBottles.push(this.returnedClonedArrayBottles[0]);
    }
  }
}

我可以使用以下方法删除任何Array的任何索引:

removeRow(index: number, type: string, event: Event): void {
  event.stopPropagation();
  if (type == 'order') {
    // Cleans the reference 'count' value.
    this.orderedBottles[index].count = null;
    this.orderedBottles.splice(index, 1);
  } else {
    this.returnedBottles[index].count = null;
    this.returnedBottles.splice(index, 1);
  }
}

我可以使用2个单独的按钮推送这两个数组中的任何一个:AddOrder()AddReturnOrder()(相同的代码):

addOrder(event: Event): void {
  event.stopPropagation();
  // Limits to the number of types
  if (this.orderedBottles.length < this.orderedClonedArrayBottles.length) {
    let index = this.getAvailableIndex(this.orderedBottles, this.orderedClonedArrayBottles);
    this.orderedBottles.push(this.orderedClonedArrayBottles[index]);
  }
}

为了避免在我的数组中推送现有引用,我使用以下方法来获取第一个尚未显示的可用索引:

/**
 * Gets the first available index from 2 arrays containing the same references.
 *
 * @param {Object[]} displayedArray Array containing the occupied indexes
 * @param {Object[]} referenceArray Array containing all the indexes
 * @return {number} Index of the first available position
 */
getAvailableIndex(displayedArray: Object[], referenceArray: Object[]): number {
  let index: number = null;
  // Gets the available indexes of Bottles by filtering the referenceArray with the displayedArray
  let availablePositions: Object[] = referenceArray.filter(element => displayedArray.indexOf(element) < 0);
  // Return the first position available
  return index = referenceArray.indexOf(availablePositions[0]);
}

以下是相应的HTML:(在Plunkr中更清晰)

  <div fxLayout="row" style="max-width: 80%">
    <div fxLayout="column" style="min-width: 50%">

      <div fxLayout="row" style="max-width: 100%" *ngFor="let bottle of orderedBottles; let i = index">
        <md-select class="select" placeholder="Select bottle type" name="orderedTypeSelect_{{i}}" [(ngModel)]="orderedBottles[i].typeId">
          <md-option class="options" *ngFor="let type of bottleArray" [value]="type.typeId">
            {{ type.name }}
          </md-option>
        </md-select>

        <md-input-container class="container">
          <input md-input type="number" name="orderedBottleInput_{{i}}" autocomplete="off" [(ngModel)]="orderedBottles[i].count"
          step="1" min="0" max="99">
        </md-input-container>

        <button class="button-row" type="button" (click)="removeRow(i, 'order', $event)">-</button>

        {{orderedBottles[i].typeId}} -
        {{orderedBottles[i].count}}
      </div>

    </div>


    <div fxLayout="column" style="min-width: 50%">

      <div fxLayout="row" style="max-width: 100%" *ngFor="let bottle of returnedBottles; let j = index">
        <md-select class="select" placeholder="Select bottle type" name="returnedTypeSelect_{{j}}" [(ngModel)]="returnedBottles[j].typeId">
          <md-option class="options" *ngFor="let type of bottleArray; let z = index" [value]="bottleArray[z].typeId">
            {{ bottleArray[z].typeId }}
          </md-option>
        </md-select>

        <md-input-container class="container">
          <input md-input type="number" name="returnedBottleInput_{{j}}" autocomplete="off" [(ngModel)]="returnedBottles[j].count"
          step="1" min="0" max="99">
        </md-input-container>

        <button style="margin-top: -20px;" class="button-row" type="button" (click)="removeRow(j, 'return', $event)">-</button>

        {{returnedBottles[j].typeId}} -
        {{returnedBottles[j].count}}
      </div>

    </div>
  </div>

  <div class="margin">
    <button md-raised-button type="button" class="submit-button" (click)="addOrder($event)">Add Order</button>
    <button md-raised-button type="button" class="submit-button" (click)="addReturnOrder($event)">Add Return Order</button>
  </div>

1 个答案:

答案 0 :(得分:2)

使用trackBy来避免混乱:

*ngFor="let bottle of orderedBottles; let i = index; trackBy: trackByFn"

trackByFn(index) {
    return index;
}

它还可以提高您的表现

<强> Modified Plunker

另见

相关问题