5

How can I break from an *ngFor loop in Angular 4?

I just want this loop to break after it executes once.

  <div *ngFor="let thing of things">
    <div *ngIf="thing == otherThing">
      <h4>Sub Title</h4>
      ***BREAK HERE***
    </div>
  </div>
Jus10
  • 14,519
  • 21
  • 52
  • 77

3 Answers3

2

You can't break *ngFor.

But you can build a custom pipe to filter the data.

But as Jus10's said, the better way is to do it in ts-file.

augustine
  • 538
  • 4
  • 15
1

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

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

As ausutine mentioned:

You can't 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
  • 1
    it doesn't break the loop, it keeps on iterating over products array. But, in the practice it does the job, though not so efficiently – B. León Jun 15 '19 at 20:01
  • You are absolutely right Leon. Highlighted point says the same that you can't break the loop. – Usama nadeem Jun 19 '19 at 04:19
0

Please try this slice, scenario (you want to run loop for n elements)

<div *ngFor="let thing of things.slice(0,1)">
<div *ngIf="thing == otherThing">
  <h4>Sub Title</h4>
</div>