Ionic:ngFor 中的 ngIf 语句不起作用

Ionic : ngIf statement inside a ngFor not working

我想借助 ngfor 显示数据库中的数据。我想使用 ngif 来实现一些显示条件。

我的代码:

<ion-grid  *ngFor="let chat of ChatListArray">
  <ion-row *ngIf="chat.status == 'Incoming'">
    <ion-col >
      <div>
       {{chat.msg}}
      </div>
    </ion-col>
  </ion-row>
  <br>
  <ion-row *ngIf="chat.status == 'Outgoing'"> 
    <ion-col >
      <div>
       {{chat.msg }}
      </div>
    </ion-col>
  </ion-row>
</ion-grid>

但它不起作用。如何正确使用if语句请帮忙

{{chat.msg }} 不显示任何数据。 但在 ngif 之外它的工作原理。

我的 json 数组:

您的代码看起来不错,应该可以工作。您似乎在 ChatListArrayIncomming 中输入了错误。也许 Incoming?

您可以做的是使用 json 管道查看 chat.status 的值以了解您正在迭代的值:

<ion-grid  *ngFor="let chat of ChatListArray">
    <div>
       {{chat | json }}
    </div>
</ion-grid>

您的数组仅包含一个对象消息,因此这就是您看不到任何消息的原因。例如。 ngIf=chat.status == 'Incoming',它起作用了,它会得到这个对象 {"status":"Outgoing"},但是这个对象没有任何 msg 对象,因为这个对象 msg 是迭代中的下一个:

[
{"id":1},
{"number":"+..."},
{"status":"Outgoing"},
{"msg": "hello"},

{"id":2},
{"number":"+..."},
{"status":"Incoming"},
{"msg": "hello"},

{"id":3},
{"number":"+..."},
{"status":"Outgoing"},
{"msg": "hello"},
]

如果您的数组中有这样的对象,它将起作用:

[
{"id":1, "number":"+...", "status":"Outgoing", "msg": "hello"},

{"id":2, "number":"+...", "status":"Incoming", "msg": "hello"},

{"id":3, "number":"+...", "status":"Outgoing", "msg": "hello"}
]