Angular 7-使用ngFor使数组中的最后一个项目成为链接

问题描述 投票:0回答:2

我有一个菜单项列表,我想将数组中的最后一个项目链接。

现在菜单项是从组件构建的,但是我不确定如何使数组中的最后一项成为链接。

ActionMenuItem.component.html

  <div *ngIf="expanded">
  <actionmenuitem *ngFor="let child of line.children" [line]="child" (inWorkspace)="toWorkspace($event)"></actionmenuitem>

ActionMenuItem.Component.ts

  onSelect(){
// If it has children, expand them && flip carat.
if(this.line.children.length > 0){

  this.expanded = !this.expanded;

  if(this.iconName == "expand_more"){
    this.iconName = "expand_less"
  } else {
    this.iconName = "expand_more"
  }

} else {
  this.inWorkspace.emit(this.line);
}
javascript angular typescript angular7 angular8
2个回答
1
投票

尝试这样:

Working Demo

<ng-container *ngFor="let child of line.children;let i=index">

    <actionmenuitem *ngIf="i != (line.children.length-1)" [line]="child" (inWorkspace)="toWorkspace($event)">
    </actionmenuitem>

    <a [routerLink]="[child]" *ngIf="i == (line.children.length-1)">{{child}}</a>
</ng-container>

0
投票

Angular公开了您可以使用的以下变量:

  • 第一
  • 最后
  • even
  • 索引
  • 奇数

因此,使最后一项成为链接,您可以执行此操作

<div *ngFor="let child of line.children; let last = islast">
   <actionmenuitem *ngIf="islast" [line]="child" 
(inWorkspace)="toWorkspace($event)">
    </actionmenuitem>
</div>
© www.soinside.com 2019 - 2024. All rights reserved.