我有一个列表,让我们称之为数字答案,并获取该数组的切片并显示其中的值。我想做的是记下我想要的位置在数组中的位置......
<div *ngFor="let item of answers | slice: 3:6" class="float-left square">
{{ item }}
</div>
Run Code Online (Sandbox Code Playgroud)
我努力了:
<div *ngFor="let item of answers | slice: 3:6; index as i" class="float-left square">
{{ item }} {{ i }}
</div>
Run Code Online (Sandbox Code Playgroud)
但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>
Run Code Online (Sandbox Code Playgroud)
我所做的就是手动输入起始值来选择方块,并创建一个 ID,这样我就可以找到唯一的 Div(看起来仍然是倒退的)。
在我的 .ts 文件中,我创建了一个记住变量并创建了一个 pickSquare 添加了一个类来突出显示该正方形已被选中。然后,通用找到任何“红色”,让我们称之为它,以清除棋盘并在事后放置一个新的“红色”挑选的方块。
作为“新人”,我希望我能接受所有答案,因为你们都给了我很大的帮助。
基于 ngFor 构建您自己的循环,以从数组返回原始索引,并直接在循环中设置开始、结束切片值。
创建文件for-with-slice.directive.ts并设置此代码。这是原始的 ngFor,带有添加切片选项和 realIndex 变量。
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;
}
Run Code Online (Sandbox Code Playgroud)
模块中的声明和导出:
import { NgForWithSliceOf } from './for-with-slice.directive'
...
@NgModule({
imports: [ ... ],
declarations: [ ... NgForWithSliceOf ],
bootstrap: [ ... ],
exports: [NgForWithSliceOf],
})
Run Code Online (Sandbox Code Playgroud)
在模板中使用:
<div *ngForWithSlice="let thing of allTheThings; sliceStart: 2; sliceEnd: 7; realIndex as i; index as j">
{{'Value: ' + thing}} {{'realIndex: ' + i}} {{' index: ' + j }}
</div>
Run Code Online (Sandbox Code Playgroud)
组件示例数组:
allTheThings = [0, 1, 2, 2,3,6,2,1];
Run Code Online (Sandbox Code Playgroud)