如何在 *ngIf 中使用函数,导致无限循环 Angular 2

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

我一直在尝试 Angular2/4 做一些事情,比如当页面呈现时它会检查文件,如果文件存在,它会显示一个复选框图标,而如果它不存在,则会显示一个下载图标。但它会遇到无限循环,建议使用布尔变量,但我的元素是动态的,可以有任意数量的下载链接,所以预定义变量不是一个选项。

A​​ngular2 代码

<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 函数

 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;
   });
 }

这不是无限循环。每次 Angular 运行变更检测时,它都会评估绑定中的表达式,这意味着您的函数被调用得非常频繁。

绑定到组件模板中的函数在 Angular 中通常不是一个好主意。而是将函数调用的结果分配给一个字段并绑定到该字段。

此处您没有从方法 fileExists(url) 返回任何内容。无论您要返回什么 true/false,都在回调处理程序中并返回给调用函数(这里是 Promise)。因此,调用 fileExists(url) 将始终得到 void 并评估为 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()"
  });
}

您可以使用ngIf中的简单函数,但必须确保returns正确。

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