14

I am trying to iterate array using *ngFor inside the template and searching for an element based on the key, using *ngIf. Now when the condition is matched with the key I want to break the *ngFor. I wondered if there any option in angular2 to break the ngFor loop based on condition.

Varun Sukheja
  • 6,170
  • 5
  • 51
  • 93
deen
  • 2,185
  • 7
  • 29
  • 53
  • I guess you can get an inspiration from this [answer](http://stackoverflow.com/questions/34164413/how-to-apply-filters-to-ngfor) – Ismail H Oct 07 '16 at 07:02

3 Answers3

13

I had to break the loop so i followed the following approach.

I don't know whether it's helpful or not still sharing that piece of code.

As Gunter mentioned:

There is no option to break ngFor.

It's just an alternate way to do so.

<ng-container *ngFor="let product of products; let i = index">
    <div *ngIf="i < 10">
        <span> product.name </span>
    </div>
</ng-container>
Usama nadeem
  • 411
  • 7
  • 15
7

There is no option to break ngFor. You can use a custom pipe that doesn't return values after the element where the condition is met.

For more concrete approaches please provide more concrete information about what you actually try to accomplish.

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
3

Since there is no option to break for ngFor, You can try an alternative way though.

This way doesn't actually break the loop but skips the next element to display/run after certain condition is satisfied whether the next element is true of false .

In page.html

<div class="loop-div" *ngFor="let element of array">
 <div class="check-div" *ngIf="displayCondition(checkValue, element.value)" > {{displayValue}} </div>
</div>

In page.ts

checkSameValue;   //initialised before constructor
displayCondition(checkValue, elementValue) {
        if(this.checkSameValue && this.checkSameValue == checkValue) {
          return false;
        }
        if(checkValue == elementValue) {
          this.checkSameValue = checkValue;
          return true;
        }
      }

This particular code escapes the further .check-div to display even if the condition is satisfied. i.e once the condition is satisfied the loop doesn't display until and unless the the checkValue is different.

KCP
  • 929
  • 9
  • 29