单击使用角度 8 反应形式添加新时如何将新行置于顶部

How to bring new row to top when clicked on add new using angular8 reactive forms

我正在使用 angular8 反应形式来绑定数据并在单击添加新按钮时添加新行,但是在这里当我单击添加新按钮时,新输入行位于编辑部分的底部,但我希望它出现在添加新按钮的正下方,我也附上了演示。

HTML:

<button
    type="button"
    class="btn btn-outline-primary switchView active"
    (click)="addOpportunityDetails()"
  >
    <i class="fas fa-plus"></i> Add new
  </button>

 <form [formGroup]="opportunitiesForm" *ngIf="opportunitiesForm">
    <ng-container formArrayName="opportunitesx">
      <div
        class="row mt-5"
        *ngFor="
          let item of opportunitiesForm.get('opportunitesx')['controls'];
          let i = index
        "
        [formGroupName]="i"
      >
        <div class="col-md-12" *ngIf="item.get('showHeader').value">
          {{ item.get('header').value }}
        </div>

        <div class="col-3">
          <input
            type="text"
            class="form-control"
            placeholder="Quote Count"
            formControlName="quoteCount"
            maxlength="4"
          />
        </div>

        <div class="col-3">
          <input
            type="text"
            class="form-control"
            placeholder="Policy Count"
            formControlName="policyCount"
            allowNumberOnly
            maxlength="4"
          />
        </div>

        <div class="col-3">
          <input
            type="text"
            class="form-control"
            placeholder="Written Premium"
            formControlName="writtenPremium"
          />
        </div>
      </div>
    </ng-container>
  </form>

TS:

public addOpportunityDetails() {
    this.opportunitesx.push(this.createOpportunityInformation());
    this.isEditValue = this.opportunitesx ? this.opportunitesx.length : 0;
  }

Demo

您可以使用 unshift 方法。但是,它不能直接在 formArray 上使用。为此,您需要使用 formArray.controls.

public addOpportunityDetails() {
    this.opportunitesx.controls.unshift(this.createOpportunityInformation());
    this.isEditValue = this.opportunitesx ? this.opportunitesx.length : 0;
  }

参考资料:- https://angular.io/api/forms/FormArray