user2024080
user2024080

Reputation: 5101

How to add the element conditionally in `*ngFor` loop?

I am looping through a li element. in the first li require to have a child as span element. how to achieve that?

here is my try:

    <ul class="country-list">
            <li *ngFor="let country of supportedCountries; let i = index ">
                    <span *ngIf="i===0" class="drop-down">{{country}}</span> {{country}}
            </li>
   </ul>

Upvotes: 0

Views: 1921

Answers (2)

Lia
Lia

Reputation: 11982

you can use ng-container with no extra DOM element and every value of i you want:

<ul class="country-list">
    <li *ngFor="let country of myArray; let i = index ">
        <ng-container *ngIf="i===0">
            <span class="drop-down">salam</span> 
        </ng-container>
    </li>
</ul>

Upvotes: 2

Carsten
Carsten

Reputation: 4208

the NgForOf directive also has a 'first' variable:

<ul class="country-list">
  <li *ngFor="let country of supportedCountries; let first = first ">
     <span *ngIf="first === true" class="drop-down">{{country}}</span>      
     <ng-container *ngIf="first === false">{{country}}</ng-container>
  </li>
</ul>

Upvotes: 2

Related Questions