在ngIf中如何检查数组键是否存在?

时间:2019-05-10 12:51:19

标签: angular

files是对象的数组。它始终具有name属性,但可能具有或不具有progress属性。进度具有类型编号的值。有没有办法检查ngIf中是否存在进度:-

<tr *ngFor="let file of files; let i=index;">
  <td>{{file.name}}</td>
  <td *ngIf="file.progress"> Show This if progress doesnt exist</td>
  <td *ngIf="file.progress"> Show This if progress exists</td>
<tr>

4 个答案:

答案 0 :(得分:0)

您可以尝试这样。您可以使用<ng-template>并实现else条件。因此无需两次实施*ngIf

 <tr *ngFor="let file of files; let i=index;">
    <td>{{file.name}}</td>
    <td *ngIf="file?.progress; else elsePart"> Show This if progress doesnt exist</td>
    <ng-template #elsePart>
    <td> Show This if progress exists</td>
    </ng-template>
 <tr>

答案 1 :(得分:0)

是的,您可以使用Object​.prototype​.has​OwnProperty()方法检查文件对象是否具有属性progress:-

<tr *ngFor="let file of files; let i=index;">
    <td>{{file.name}}</td>
    <td *ngIf="!file.hasOwnProperty('progress')">Show This if progress doesnt exist</td>
    <td *ngIf="file.hasOwnProperty('progress')">Show This if progress exists</td>
<tr>

答案 2 :(得分:0)

您可以这样写

<tr *ngFor="let file of files; let i=index;">
    <td>{{file.name}}</td>
    <td *ngIf="file.progress.length === 0"> Show This if progress doesnt exist</td>
    <td *ngIf="file.progress.length > 0"> Show This if progress exists</td>
<tr>

确保数组格式类似于以下格式,并且进度为字符串。

const files = [
  {
    name: 'ram',
    progress: 'jhsdgfshgdfjhsgdfg',
  },
  {
    name: 'ramdfgdrf',
    progress: '',
  },
  {
    name: 'ramdfg',
    progress: 'shgdfjhsgdfg',
  },
  {
    name: 'rdsfgdam',
    progress: 'hgdfjhsgdfg',
  }
];

答案 3 :(得分:0)

<tr *ngFor="let file of files; let i=index;">
    <td>{{file.name}}</td>
    <td *ngIf="!file['progress']">Show This if progress doesnt exist</td>
    <td *ngIf="file['progress']">Show This if progress exists</td>
<tr>

我将尝试访问该属性,如果该属性不存在,则它将返回undefined并因此返回false。