gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 04:30:41 27 4
gpt4 key购买 nike

我有一个列表,可以将其称为数字答案,并获取该数组的切片并在那里显示值。我想做的也是注意我想要在数组中的位置......

<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>

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

在我的 .ts 文件中,我创建了一个记住变量并创建了一个 pickSquare 添加了一个类以突出显示该正方形已被选中。然后一个通用的找到任何“红色”让我们调用它,以清除棋盘并在事后放置一个新的“红色”选择方 block 。

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

最佳答案

基于 ngFor 构建自己的循环,从数组中返回原始索引,并直接在循环中设置开始、结束切片值。

创建文件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

关于Angular 5 - 切片数组上 ngFor 的子索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49266791/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com