Tom Cohen
Tom Cohen

Reputation: 163

:first-child with *ngFor is not working properly

i am trying to use :first-child on navigation bar buttons but it works on all nav's buttons from some reason. the same works with :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%)'
}]

Upvotes: 0

Views: 3218

Answers (2)

danday74
danday74

Reputation: 57036

ngFor has a built-in "first" and "last"

This is from the docs:

<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>

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

You can use first and last in conjunction with [ngClass] or [ngStyle]

FYI first and last are just boolean values.

Upvotes: 5

Mosh Feu
Mosh Feu

Reputation: 29277

This is happening because that all of .tab is actually the first-child of his parent (the ul).

You probably wanted to put the *ngFor on the li node so it will repeat for the menu items.

If not, please post your output html so we could see what's happening here.

Upvotes: 1

Related Questions