Search code examples
angularcollectionsgoogle-cloud-firestoreangularfire5

AngularFire - How to display Firestore key and value in collection query


I'm using a standard AngularFire collection query. However a project requirement has dictated that instead of explicit binding firestore nodes and values directly in the HTML (as seen in the first HTML snippet below), that we instead bind the returned key and value so that if any new fields are added in Firestore, I won't need to update my project to display those items.

Is there a way, with the standard AngularFire query to bind the key and value of each returned result in the HTML?

user.component.ts

  getUsers(){
    this.usersCollection = this.afs.collection<User>('users');
    this.users = this.usersCollection.snapshotChanges().pipe(
      map(actions => actions.map(a => {
        const data = a.payload.doc.data() as User;
        const id = a.payload.doc.id;  
        return { id, ...data };
      }))
    );
  }

HTML

<ul>
    <li *ngFor="let user of users | async">
        <div>{{ user.name }}</div>
        <div>{{ user.dob }}</div>
        <div>{{ user.id }}</div>
    </li>
</ul>

Desired Result

<ul>
    <li *ngFor="">
        <div>{{key}} / {{ value }}</div>
    </li>
</ul>

Solution

  • There is a pipe called | keyvalue (angular 6+). So what you can do is:

    <ul>
        <li *ngFor="let user of users | async">
            <div *ngFor="let userinfo of user | keyvalue">
              {{ userinfo.key}}: {{userinfo.value}}
            </div>
        </li>
    </ul>