如何在Angular 7 for循环中找到数组的第一项和最后一项?

时间:2019-04-04 23:28:48

标签: javascript html angular typescript

我正在Angular for循环中创建项目列表。该列表需要具有允许用户上下移动列表项的按钮。如果该项目已经在列表顶部,则我想隐藏该按钮以将其上移。如果该按钮在列表的底部,则我想隐藏该按钮,该按钮将允许用户向下移动该项目。

这是描述列表项的子组件的HTML。鉴于我没有数组项目的索引,此方法将无法工作。我在父组件中使用trackBy方法,但是我不确定它是否可以在这里应用。

<div style="margin:auto; margin-right:15px;">
        <span  style="display: inline-grid;">
            <a *ngIf="expiredIncentive[i] > 0" (click)="moveUp(incentive)" title="Move-up">
                    <i class="fa fa-2x fa-sort-up"></i>
                </a>
                <a *ngIf="expiredIncentives[i] < expiredIncentives.length" (click)="moveDown(incentive)" title="Move-down">
                    <i class="fa fa-2x fa-sort-down"></i>
            </a>
        </span>
    </div>

TS

@Component({
    selector: 'incentive-widget',
    templateUrl: 'incentive.widget.html',
})

export class IncentiveWidget {
      @Input()
expiredIncentives: any;

这是我正在使用子级“激励”组件的父级组件。我通过属性绑定来绑定“ expiredIncentives”,这样我就可以访问子组件中数组的长度。

<incentive-widget *ngFor="let incentive of expiredIncentives;trackBy: trackByFn"
                                  [isEditMode]="true" [incentive]="incentive" [expiredIncentives]="expiredIncentives"
                                  [dealerId]="_dealerId" [isExpiredIncentive]="true" 
                                  (clickedIncentiveUp)="clickedIncentiveUp(incentive)"
                                  (clickedIncentiveDown)="clickedIncentiveDown(incentive)">
                </incentive-widget>

1 个答案:

答案 0 :(得分:0)

您可以将* ngFor与firstlast用作变量,它是boolean

然后您可以比较此值以验证它是否为first

<incentive-widget *ngFor="let incentive of expiredIncentives;trackBy: trackByFn; let first = first; let last  = last ">