Angular 5 - ngFor over切片数组的子索引

时间:2018-03-13 22:23:48

标签: angular

我有一个列表让我们称它为数字的答案,并且正在拍摄该数组并显示其值。我想做的还是注意我想要在阵列中的位置......

<div *ngFor="let item of answers | slice: 3:6" class="float-left square">
    {{ item }}
</div>

我试过了:

<div *ngFor="let item of answers | slice: 3:6; index as i" class="float-left square">
    {{ item }} {{ i }}
</div>

i分别导致 0,1,2 而不是所需的 3,4,5

思考?使用索引的想法很可能是假的,因为我在询问之前就这么说了。

我的解决方案

所以很多人都有一些很棒的想法;但是,真的不合适。

<div *ngFor="let item of answers | slice: 60:63; index as i"
                (click)="pickSquare(60 +i)" id="{{60 + i}}"
                class="float-left square">{{item}}</div>

我所做的是手动输入选择正方形的起始值,并创建一个ID,这样我就可以找到唯一的Div(仍然看起来像是向后)。

在我的.ts文件中,我创建了一个记忆变量并创建了一个pickSquare添加了一个类来突出显示该方块被选中。然后一个通用发现任何“红色”让我们调用它,清除板并在事后放置一个新的“红色”挑选方块。

作为“新人”,我希望我能接受所有答案,因为你们都很有帮助。

4 个答案:

答案 0 :(得分:0)

您只需使用偏移量(3)

填充索引

这样的事情:

<div *ngFor="let item of answers | slice: 3:6; index as i" class="float-left square">
    {{ item }} {{ i+3 }}
</div>

StackBlitz Example

答案 1 :(得分:0)

使用切片,您正在查看新的切片数组,以便重置索引。在控制台类型[1,2,3,4,5,6,7] .slice(3,6)中,看看会发生什么。如果3是变量,你可以这样做:

<div *ngFor="let item of answers | slice: offset:6; index as i" class="float-left square">{{item}} {{i + offset}}</div>

答案 2 :(得分:0)

有两种方法可以做到这一点。

  1. 您可以在插值时间内将其添加到索引中。

    <div *ngFor="let item of answers | slice: 3:6; index as i" class="float-left square"> {{ item }} {{ i }} </div>

  2. 您可以创建子组件并传递切片的起点值,要打印的值和元素的索引。

  3. Here is the stackblitz第二点。

    希望这会有所帮助!!

答案 3 :(得分:0)

基于ngFor构建自己的循环,从数组中返回原始索引,并在循环中直接设置start,end slice值。

创建文件for-with-slice.directive.ts并设置此代码。这是带有添加切片选项和realIndex变量的原始ngFor。

import { ChangeDetectorRef, Directive, DoCheck, EmbeddedViewRef, Input, IterableChangeRecord, IterableChanges, IterableDiffer, IterableDiffers, NgIterable, OnChanges, SimpleChanges, TemplateRef, TrackByFunction, ViewContainerRef, forwardRef, isDevMode } from '@angular/core';

/**
 * @stable
 */
export class ngForWithSliceOfContext<T> {
  constructor(
    public $implicit: T,
    public ngForWithSliceOf: NgIterable<T>,
    public index: number,
    public realIndex: number,
    public sliceStart: number,
    public sliceEnd: number,
    public count: number) { }

  get first(): boolean { return this.index === 0; }

  get last(): boolean { return this.index === this.count - 1; }

  get even(): boolean { return this.index % 2 === 0; }

  get odd(): boolean { return !this.even; }
}

@Directive({ selector: '[ngForWithSlice][ngForWithSliceOf]' })
export class NgForWithSliceOf<T> implements DoCheck, OnChanges {

  @Input() ngForWithSliceOf: NgIterable<T>;
  @Input() ngForWithSliceSliceStart: number = 0;
  @Input() ngForWithSliceSliceEnd: number;
  @Input()
  set ngForTrackBy(fn: TrackByFunction<T>) {
    if (isDevMode() && fn != null && typeof fn !== 'function') {

      if (<any>console && <any>console.warn) {
        console.warn(
          `trackBy must be a function, but received ${JSON.stringify(fn)}. ` +
          `See https://angular.io/docs/ts/latest/api/common/index/NgFor-directive.html#!#change-propagation for more information.`);
      }
    }
    this._trackByFn = fn;
  }

  get ngForTrackBy(): TrackByFunction<T> { return this._trackByFn; }

  private _differ: IterableDiffer<T> | null = null;
  private _trackByFn: TrackByFunction<T>;

  constructor(
    private _viewContainer: ViewContainerRef,
    private _template: TemplateRef<ngForWithSliceOfContext<T>>,
    private _differs: IterableDiffers) { }

  @Input()
  set ngForTemplate(value: TemplateRef<ngForWithSliceOfContext<T>>) {
    if (value) {
      this._template = value;
    }
  }

  ngOnChanges(changes: SimpleChanges): void {
    if ('ngForWithSliceOf' in changes) {
      const value = changes['ngForWithSliceOf'].currentValue;
      if (!this._differ && value) {
        try {
          this._differ = this._differs.find(value).create(this.ngForTrackBy);
        } catch (e) {
          throw new Error(
            `Cannot find a differ supporting object '${value}' of type '${getTypeNameForDebugging(value)}'. NgFor only supports binding to Iterables such as Arrays.`);
        }
      }
    }
  }

  ngDoCheck(): void {
    if (this._differ) {
      const changes = this._differ.diff(this.ngForWithSliceOf);
      if (changes) this._applyChanges(changes);
    }
  }

  private _applyChanges(changes: IterableChanges<T>) {

    const insertTuples: RecordViewTuple<T>[] = [];
    changes.forEachOperation(
      (item: IterableChangeRecord<any>, adjustedPreviousIndex: number, currentIndex: number) => {
        let endOfArray = this.ngForWithSliceSliceEnd;
        if (typeof endOfArray === "undefined") {
          endOfArray = item.currentIndex + 1;
        }
        if (item.currentIndex >= this.ngForWithSliceSliceStart && item.currentIndex < endOfArray) {
          if (item.previousIndex == null) {
            const view = this._viewContainer.createEmbeddedView(
              this._template,
              new ngForWithSliceOfContext<T>(null!, this.ngForWithSliceOf, -1, -1, 0, 0, -1), currentIndex - this.ngForWithSliceSliceStart );
            const tuple = new RecordViewTuple<T>(item, view);
            insertTuples.push(tuple);
          } else if (currentIndex == null) {
            this._viewContainer.remove(adjustedPreviousIndex);
          } else {
            const view = this._viewContainer.get(adjustedPreviousIndex)!;
            this._viewContainer.move(view, currentIndex);
            const tuple = new RecordViewTuple(item, <EmbeddedViewRef<ngForWithSliceOfContext<T>>>view);
            insertTuples.push(tuple);
          }
        }
      });

    console.error(insertTuples)
    for (let i = 0; i < insertTuples.length; i++) {

      this._perViewChange(insertTuples[i].view, insertTuples[i].record);
    }

    for (let i = 0, ilen = this._viewContainer.length; i < ilen; i++) {
      const viewRef = <EmbeddedViewRef<ngForWithSliceOfContext<T>>>this._viewContainer.get(i);
      viewRef.context.index = i;
      viewRef.context.realIndex = i + this.ngForWithSliceSliceStart;
      viewRef.context.count = ilen;
    }

    changes.forEachIdentityChange((record: any) => {
      const viewRef =
        <EmbeddedViewRef<ngForWithSliceOfContext<T>>>this._viewContainer.get(record.currentIndex);
      viewRef.context.$implicit = record.item;
    });
  }

  private _perViewChange(
    view: EmbeddedViewRef<ngForWithSliceOfContext<T>>, record: IterableChangeRecord<any>) {
    view.context.$implicit = record.item;
  }
}

class RecordViewTuple<T> {
  constructor(public record: any, public view: EmbeddedViewRef<ngForWithSliceOfContext<T>>) { }
}

export function getTypeNameForDebugging(type: any): string {
  return type['name'] || typeof type;
}

模块中的声明和导出:

import { NgForWithSliceOf } from './for-with-slice.directive'
...
@NgModule({
  imports:      [ ... ],
  declarations: [ ... NgForWithSliceOf ],
  bootstrap:    [ ... ],
  exports: [NgForWithSliceOf],
})

在模板中使用:

<div *ngForWithSlice="let thing of allTheThings; sliceStart: 2; sliceEnd: 7; realIndex as i; index as j">
  {{'Value: ' + thing}} {{'realIndex: ' + i}} {{' index: ' + j }}
</div>

组件示例数组:

allTheThings = [0, 1, 2, 2,3,6,2,1];

StackBlitz Example