Angular 7 - 使用 ngFor 创建数组 A 中的最后一项 Link

Angular 7 - Make Last Item in Array A Link Using ngFor

我有一个菜单项列表,我想将数组中的最后一项设置为 link。

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

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);
}

这样试试:

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>

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

  • 第一
  • 最后
  • 甚至
  • 索引
  • 奇数

所以要使最后一项成为 link 你可以这样做

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

您只需要修复最后的标志分配:

  • 让 isLast = 最后一个 或
  • 上次为上次