Item in loop is undefined

Hi All,

I have an issue that I don’t understand, and if anyone can help, I would appreciate it.

I am using Ionic2 with Meteor/MongoDb.

I have a cursor:

private messages: Mongo.Cursor<Message>;

On the server I do an insert:

      chatId: chatId,
      senderId: senderId,
      content: content,
      readByReceiver: false,
      createdAt: new Date()

It triggers an observable as expected:

          added: (message) => this.addMessageToLocal(message)
  private addMessageToLocal(newMessage: Message): void {
     // here I print the message, and it is as expected

Also, I do a forEach through the messages, and they are all populated as expected.


My problem is in the html. I loop trough the messages cursor. It displays each item as expected. Until I add a message (as above). Then the message from the html is undefined.

		<template ngFor let-message [ngForOf]="messages">
				<div *ngIf="!exists(message)" class="message-wrapper">
					<div *ngIf="message.changeDate">
						<center><span class="message-datetime">{{message.createdAt | amDateFormat: 'DD MMM YYYY'}}</span></center>
					<div [class]="'message message-' + message.ownership">
						<div class="message-content">server:{{message.content}}</div>
						<span class="time-tick">
        <span *ngIf="message" class="message-timestamp">{{message.createdAt | amDateFormat: 'h:mm a'}}</span>
						<div *ngIf="message && message.readByReceiver && senderId == message.senderId">
							<span class="checkmark">
                <div class="checkmark_stem"></div>
                <div class="checkmark_kick"></div>

The final message item in the loop (the new one added), is undefined. i.e. In the *ngIf="!exists(message)" function called from the html, I print the message, and its’s undefined.

So in the html I loop over the messages Cursor, and the new one is undefined. However, if even in the same function (exists()), I loop over the messages Cursor again, just to test it, none of the items are undefined.


Please can anyone suggest what I can do to not have the last item in the Cursor as undefined?


Not the core issue, but you’re going to run into trouble with ngc unless you make that messages public. Component properties referenced in templates cannot be private.

1 Like

@rapropos, thank you, I will change them to public.

I am getting something I don’t understand.

When I call a function from the html as follows, message is not undefined:

{{ formatMessage(message) }}

But if I call a function as follows, it is undefined:


I solved this by using:

changeDetection: ChangeDetectionStrategy.OnPush,

But I still think there may be a bug in Angular