我一直试图在Angular2/4中创建类似于页面呈现文件时的内容,如果文件存在,则显示复选框图标,如果不存在,则显示下载图标。但是它会运行到无限循环中,建议使用布尔变量,但是我的元素是动态的,可以有任意数量的下载链接,因此预定义变量不是一个选项。
Angular2码
<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;
});
}
发布于 2017-10-01 00:06:53
在这里,您将从方法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
中使用简单函数,但必须确保它正确返回。
现在,在上面的例子中,monkey-patched承诺是能够触发变化检测的东西,因为承诺是通过角Zone.js实现的。
您可以在Angular2+ Change at https://blog.thoughtram.io/angular/2016/02/22/angular-2-change-detection-explained.html上获得更多知识。
发布于 2017-09-30 15:02:54
这不是无限循环。每次角运行变化检测时,它都会评估绑定中的表达式,这意味着您的函数经常被调用。
在角度上,绑定到组件模板中的函数通常是个坏主意。相反,将函数调用的结果分配给一个字段并绑定到该字段。
https://stackoverflow.com/questions/46507760
复制