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
    .collection('eventList')
    .valueChanges();
  }
}

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
    .collection('eventList')
    .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 :-)

By the way, do you want to jump-start your development using the Firebase modular SDK with AngularFire?

Download my free book that will take you from creating an app to properly using Firebase Auth and Firestore.

Download the book now