user8866396
user8866396

Reputation:

Access array with *ngFor Angular v5

I have some JSON data in Firebase and I'm trying to loop through the data with *ngFor in Angular v5.

The object looks like this:

{
    "events": [
        {
            "Event-time": "09:30",
            "Event-name": "Morning Session",
            "Location": "Alexander Room",
            "Speaker-image": "https://z4e3q7e996-flywheel.netdna-ssl.com/wp-content/uploads/2017/07/TeamPhotosIan.png",
            "Speaker-name": "Ian Broom",
            "Speaker-title": "CEO & Founder"
        },
        {
            "Event-time": "11:30",
            "Event-name": "Morning Session II",
            "Location": "Coffee Room",
            "Speaker-image": "https://z4e3q7e996-flywheel.netdna-ssl.com/wp-content/uploads/2012/07/TeamPhotosben.png",
            "Speaker-name": "Ben Wynne-Simmons",
            "Speaker-title": "Head of Growth & Marketing"
        }
   ]
}

This is my events-list.component:

export class EventsListComponent implements OnInit {
    eventsObservable: Observable<any[]>;

    constructor(private db: AngularFireDatabase) { }

    ngOnInit() {
        this.eventsObservable = this.getEvents('/events');
    }

    getEvents(listPath): Observable<any[]> {
        return this.db.list(listPath).valueChanges();
    }
}

I'm trying to loop through like so:

<ul>
    <li *ngFor="let event of eventsObservable | async">
        <p>{{event.Event-name}}</p>
    </li>
</ul>

What gets printed out is NaN.

I don't know how to access and display the data.

Please help! Thanks!

Upvotes: 1

Views: 773

Answers (2)

Pac0
Pac0

Reputation: 23174

The problem is to access a field that contains the sign -.

It is interpreted as a mathematical substraction (and since neither event.Event nor name is a number, event.Event - name gives NaN (NotANumber).

To access such a field with special characters in name, you have to use the brackets notation :

<p>{{event["Event-name"]}}</p>

Also, as other answer tells, you have to iterate on your array directly. It's not very clear to me how you get your observable in your answer. If you get an Observable out of the big object, then you should .map your observable to its events field.

This will give you another observable, and you should iterate on the latter.

Upvotes: 1

Sajeetharan
Sajeetharan

Reputation: 222722

You need to access events which is an array inside eventsObservable object

<div *ngFor="let event of eventsObservable.events | async">
        <p>{{event.Event-name}}</p>
 </div>

Upvotes: 0

Related Questions