简体   繁体   中英

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>

There is a pipe called | keyvalue | 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM