繁体   English   中英

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

[英]Angular2 weird form behavior with *ngFor

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

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

工作Plunkr

注意:我在第二个阵列中显示Bottle typeId ,它清楚地显示了问题。


问题 :

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

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

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


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

我将一个包含其nametypeId气瓶数组( bottleArraytypeId到我的表单@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]);
    }
  }
}

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

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>

使用trackBy避免混乱:

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

trackByFn(index) {
    return index;
}

它还可以提高您的表现

改良的Plunker

也可以看看

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM