首页 > 解决方案 > Angular 5 ngFor let i=index+3

问题描述

有没有办法将索引设置为不从 0 开始?或者修改它以每次添加一些数字?

我有一个 8 数组。我需要将它分成两个 4 组,但仍将其留在一个集合中,因为它也是一种嵌套的反应形式,并且项目的顺序是有意义的。

所以,我只需要将它分成两组并将其嵌套在材料设计的扩展面板中。

到目前为止一切顺利,但是..

第二组开始,自然从0开始计数,因为从他的角度来看,这是新组的迭代。我可以通过识别项目类型中的数据来添加 trackBy 或修改 idx ,但这不是优雅的方式。

所以问题是,如何使索引从我定义的数字开始自定义。我希望这个循环从 4 位置开始..

updateEntity(event: MatAutocompleteSelectedEvent) {
  //this.idx - should start from 4 for the second part of mat-expansion-panel
  this.children.at(this.idx).patchValue({
    id: ...
  });
}
In the Parent

<mat-accordion>
  <mat-expansion-panel>
    <mat-expansion-panel-header>
      Buyer
    </mat-expansion-panel-header>
    <div *ngFor="let item of Entity | slice:0:4; let idx=index">
      <div class="row">
        <div class="col-sm">
          <entity-search [children]="form.controls.Entity" [child]="item" [idx]="idx">
          </entity-search>
        </div>
      </div>
    </div>
  </mat-expansion-panel>
  <mat-expansion-panel>
    <mat-expansion-panel-header>
      Seller
    </mat-expansion-panel-header>
    <div *ngFor="let item of isfEntity | slice:4:8; let idx=index">
      <div class="row">
        <div class="col-sm">
          <entity-search [children]="form.controls.Entity" [child]="item" [idx]="idx">
          </entity-search>
        </div>
      </div>
    </div>
  </mat-expansion-panel>
</mat-accordion>



In Entity Search:



<mat-form-field>
  <input type="text" placeholder="{{child.placeholder}}" required matInput formControlName="entityName" aria-label="Number" [formControl]="searchEntity" [matAutocomplete]="autoEntity">
  <mat-icon matSuffix>search</mat-icon>
  <mat-autocomplete #autoEntity="matAutocomplete" (optionSelected)="updateEntity($event)">
    <mat-option *ngFor="let item of searchEntityResult" [value]="item">
      {{ item.id + " " + item.entityName + " " + item.entitySecName }}
    </mat-option>
  </mat-autocomplete>
</mat-form-field>

标签: angular5angular2-formsngforangular-reactive-forms

解决方案


最后这就是我所做的

<div *ngFor="let item of Entity | slice:4:8 ; let idx2=index">
  <p [hidden]="true">{{ idx2 + 4 }}</p>
  <div class="row">
    <div class="col-sm">
      <entity-search [children]="form.controls.isfEntity" [child]="item" [idx]="idx2">
      </entity-search>
    </div>
  </div>
</div>


推荐阅读