首页 > 解决方案 > :first-child with *ngFor 无法正常工作

问题描述

我正在尝试:first-child在导航栏按钮上使用,但由于某种原因它适用于所有导航按钮。同样适用于:last-child.

html:

<div fxLayout="row" class="top-padding-30">
  <ul fxFlex="100" *ngFor="let tab of navigation_buttons;">
    <li class="tab tab-text" [ngClass]="{'active-tab': tab.isSelected == true}" (click)="selectTab(tab)" fxLayoutAlign="center center">{{tab.name}}</li>
  </ul>
</div>

scss:

.tab {
  background-color: #d2d2d2;
  padding: 18px;
  cursor: pointer;
  margin-right: 3px;
  &.active-tab {
    background-color: #452f46;
    color: #ffffff;
  }
  &:first-child {
    border-radius: 0px 15px 15px 0px;
  }
  //   &:last-child {
  //     border-radius: 15px 0px 0px 15px;
  //   }
}

ts:

navigation_buttons = [{
  isSelected: false,
  name: 'לבנה (6%)'
}, {
  isSelected: false,
  name: 'גבינה לבנה (12%)'
}, {
  isSelected: false,
  name: 'גבינות צהובות (17%)'
}, {
  isSelected: false,
  name: 'גבינה בולגרית (25%)'
}, {
  isSelected: true,
  name: 'יוגורטים (60%)'
}]

标签: cssangularhtmlcss-selectorsngfor

解决方案


ngFor 有一个内置的“first”和“last”

这是来自文档:

<li *ngFor="let user of userObservable | async as users; index as i; first as isFirst">
   {{i}}/{{users.length}}. {{user}} <span *ngIf="isFirst">default</span>
</li>

文档:https ://angular.io/api/common/NgForOf#usage-notes

您可以将 first 和 last 与 [ngClass] 或 [ngStyle] 一起使用

FYI first 和 last 只是布尔值。


推荐阅读