Js Mobile Dev About Courses Articles Youtube Services Contact

How to get the document ID with AngularFire

Libraries and Versions

Backend: Firebase v5.0.0+
Frontend: @ionic/angular v5.0.0
Backend: @angular/fire v6.0.0

AngularFire added a new cool feature in version 5.2.0, the ability to fetch a document's ID without needing to store it inside the document first.

You don't need to install any additional packages or anything like that, now the .valueChanges() method that transforms the AngularFirestoreCollection into an array receives a parameter like this:

.valueChanges({ idField: 'propertyId' });

Where idField is the parameter we're passing the .valueChanges() and the 'propertyId' is the name we want the ID's property to have inside our object.

For example, if you have a list of people, the previous code would give you a person's document like this:

  name = 'Jorge Vergara',
  propertyId = 'whatEverTheDocumentIdWas'

Let's make that example a little more real, let's say we have a collection called eventList which has a list of documents that hold the eventName.

If we want to get that collection to show as a list on our page we'd do something like this:

export class HomePage implements OnInit {
  public myEventList: Observable;
  constructor(private firestore: AngularFirestore) {}

  ngOnInit() {
    this.myEventList = this.firestore

And then in the HTML we can do this:

<h3>Name: {{ item.eventName }}</h3>

If we want to get those document's IDs to show them on the site or to use them for other things, all we need to do is a small change in out code:

ngOnInit() {
  this.myEventList = this.firestore
    .valueChanges({ idField: 'eventId' });

And now the event's ID is available inside the document as a property called eventId:

<h3>Name: {{ item.eventName }}</h3>
ID: <strong>{{ item.eventId }}</strong>

AngularFire Collection

And that's it, now you don't have to mess with the document's metadata or to store the ID inside the document when creating it.

Do let me know in the comments if this is something useful for you :-)

Become a Mobile Developer using JavaScript

Leave your email below and you'll get one or two emails a month sharing articles, videos, or courses that will help you jump-start your development with Ionic, Firebase, and Angular 🚀.

    I don't do the spam thing, you can one-click unsubscribe at any time