【问题标题】:How do I find the first and last item of an array in an Angular 7 for loop?如何在 Angular 7 for 循环中找到数组的第一项和最后一项?
【发布时间】:2019-04-04 23:28:47
【问题描述】:

我正在 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>

【问题讨论】:

    标签: javascript html angular typescript


    【解决方案1】:

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

    然后你可以比较这个值来验证它是否是first

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

    【讨论】:

    • 我在父组件中使用 trackBy 函数。但不确定如何使用“first”和“last”变量。
    • 例如,将以下代码放入激励组件 ' I'm the first element of the loop' 它将向您显示第一个元素这段文字
    • 那么 trackBy 会知道哪个是第一个,哪个是最后一个?
    猜你喜欢
    • 2010-11-02
    • 2021-08-31
    • 1970-01-01
    • 2021-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-08
    相关资源
    最近更新 更多