Angular 角度5-ngFor过切片阵列的子索引
我有一个列表,让我们称之为数字的答案,我从这个数组中提取片段并在那里显示值。我想做的是还要注意我想要在数组中的位置Angular 角度5-ngFor过切片阵列的子索引,angular,Angular,我有一个列表,让我们称之为数字的答案,我从这个数组中提取片段并在那里显示值。我想做的是还要注意我想要在数组中的位置 <div *ngFor="let item of answers | slice: 3:6" class="float-left square"> {{ item }} </div> 我所做的是手动输入开始值来拾取正方形,并创建了一个ID,这样我就可以找到唯一的Div(看起来仍然是反向的) 在我的.ts文件中,我创建了一个memory变量并创建了一
<div *ngFor="let item of answers | slice: 3:6" class="float-left square">
{{ item }}
</div>
我所做的是手动输入开始值来拾取正方形,并创建了一个ID,这样我就可以找到唯一的Div(看起来仍然是反向的)
在我的.ts文件中,我创建了一个memory变量并创建了一个pickSquare,并添加了一个类来突出显示该正方形已被拾取。然后,一个通用的查找任何“红色”让我们调用它,清除棋盘并在事实之后放置一个新的“红色”拾取方块
作为“新手”,我希望我能接受所有答案,因为你们都帮了大忙。你只需在索引中添加偏移量(3) 大概是这样的:
<div *ngFor="let item of answers | slice: 3:6; index as i" class="float-left square">
{{ item }} {{ i+3 }}
</div>
{{item}{{i+3}}
使用slice,您将看到一个新的slice数组,因此索引将被重置。在控制台类型[1,2,3,4,5,6,7]中,切片(3,6)并查看发生了什么。如果3是一个变量,您可以执行以下操作:
<div *ngFor="let item of answers | slice: offset:6; index as i" class="float-left square">{{item}} {{i + offset}}</div>
{{item}{{i+offset}
有两种方法可以做到这一点
{{item}}{{i}}
希望这有帮助 基于ngFor构建您自己的循环,以从数组返回原始索引,并直接在循环中设置开始、结束切片值 使用slice.directive.ts为创建文件
,并设置此代码。这是带有add slice选项和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;
}
在模板中使用:
<div *ngForWithSlice="let thing of allTheThings; sliceStart: 2; sliceEnd: 7; realIndex as i; index as j">
{{'Value: ' + thing}} {{'realIndex: ' + i}} {{' index: ' + j }}
</div>
这是一个很好的答案,但有一点是数字不是唯一的,有81个数字可以容纳1-9的值。我仍然无法说出我在阵列中的位置。。。公平地说,我在问题中没有提到这一点。对不起,我不明白你的意思。他说数组数据不是唯一的,所以indexOf不起作用。[3,2,3].indexOf(3)-他想要索引0还是2?@AlexMackinnon你为什么不按照自己的方式,把+3
(偏移量)添加到i
。你应该通过这种方式得到你想要的。你能提供一个什么样的答案以及为什么你想要切片的例子吗?你有所有的解决方案吗?
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];