NgFor Loop Break in Angualr2

I am trying a *ngFor array using *ngFor inside a template, and *ngFor looking for a key based element using * ngIf. Now that the condition matches the key, I want to break *ngFor . I wondered if there is any option in angular2 to break the ngFor depending on the condition.

+9
source share
3 answers

Unable to smash ngFor . You can use a custom channel that does not return a value after the element where the condition is satisfied.

For more specific approaches, provide more specific information about what you are actually trying to accomplish.

+5
source

Since there is no gap option for ngFor, you can try an alternative way.

This method does not actually break the loop, but skips the next element to display / start after a certain condition is satisfied whether the next element is 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 specific code avoids the further .check-div for display, even if the condition is met. then after the condition is met, the loop is not displayed until checkValue is checkValue .

+2
source

I had to break the loop, so I took the following approach.

I don't know if this is useful or not while I share this piece of code.

As Gunter said:

There is no way to break ngFor.

This is just an alternative way to do this.

 <ng-container *ngFor="let product of products; let i = index"> <div *ngIf="i < 10"> <span> product.name </span> </div> </ng-container> 
0
source

Source: https://habr.com/ru/post/1257836/


All Articles