Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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>
like image 953
Jus10 Avatar asked Oct 17 '22 10:10

Jus10


2 Answers

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.

like image 160
augustine Avatar answered Oct 20 '22 05:10

augustine


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>
like image 40
Usama nadeem Avatar answered Oct 20 '22 06:10

Usama nadeem