Piyush Gupta
Piyush Gupta

Reputation: 33

How to use function in *ngIf, resulting to infinite loop Angular 2

I have been trying in Angular2/4 to make something like when page renders it checks for a file and if file exists it shows a checkbox icon while if it doesnot exist then a download icon is shown. But it runs into infinite loop, it is suggested to use a boolean variable but my elements are dynamic and there can be any number of download links so predefined variables are not an option.

Angular2 Code

<div *ngFor="let item of getItems();">
  <div ngIf="fileExists(item.url); then example2 else example1"></div>
  <ng-template #example1>
    <ion-icon class="myicon" name="download" color="primary"></ion-icon>
  </ng-template>
  <ng-template #example2>
    <ion-icon class="myicon" name="checkbox" color="secondary"></ion-icon>
  </ng-template>
</div>

TypeScript function to check if file exists

 fileExists(url)
 {
   let path = "notif/"+url.substr(url.lastIndexOf('/')+1);
   this.file.checkFile(this.file.externalRootDirectory, path).then(_ => {
     console.log('File exists');    
     return true;
   }).catch(err => {
     console.log(err);
     return false;
   });
 }

Upvotes: 3

Views: 4545

Answers (2)

Somnath Sinha
Somnath Sinha

Reputation: 672

Here you are returning nothing from method fileExists(url). Whatever true/false you are returning is inside callback handler and returned to caller function (here Promise). So, calling fileExists(url) will always get void and evaluated as false

fileExists(url) {
  let path = "notif/"+url.substr(url.lastIndexOf('/')+1);
  this.file.checkFile(this.file.externalRootDirectory, path).then(_ => {
    console.log('File exists');
    return true; // "true" returned by this success callback, not "fileExists()"
  }).catch(err => {
    console.log(err);
    return false; // "true" returned by this error callback, not "fileExists()"
  });
}

You can use simple functions in ngIf, but you must ensure it returns correctly.

Now in above example, Promise is the thing which can trigger change detection as Promise is monkey-patched by Angular Zone.js.


You can get more knowledge on Angular2+ Change Detection at https://blog.thoughtram.io/angular/2016/02/22/angular-2-change-detection-explained.html

Upvotes: 0

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657466

It's not an infinity loop. Every time Angular runs change detection, it evaluates the expressions in bindings, this means your function is called very often.

Binding to functions in component templates is usually a bad idea in Angular. Instead assign the result of the function call to a field and bind to this field.

Upvotes: 5

Related Questions