Search code examples
jsonangularfirebasestring-interpolationgoogle-cloud-firestore

Can't Access JSON Properties Of Firestore Data With String Interpolation


I can't access the properties of my Firestore document during string Interpolation. The regular JSON output works fine though. Here's the code:

Working

<h3>{{ teacher | async | json }}</h3>

Output:

Output - Working


Not working

<h3>{{ teacher.name | async | json }}</h3>

and

<h3>{{ teacher.name | async }}</h3>

Output:

Output - Not Working


Typescript code

interface Teacher {
  name: string;
}

teacherDoc: AngularFirestoreDocument<Teacher>;
teacher: Observable<Teacher>;

var placeToSearch = 'Teachers/'+this.selectedTeacher;

this.teacherDoc = this.afs.doc(placeToSearch);
this.teacher = this.teacherDoc.valueChanges();

Solution

  • You're just slightly off with the async pipe. The object needs to be unwrapped first, then you call it's properties. It should look like:

    {{ (teacher | async)?.name }}
    

    Or better yet, set a template variable to avoid using the async pipe over and over:

    <div *ngIf="teacher | async as t">
      {{ t.name }}
      {{ t.field }}
      {{ t.whatever }}
    </div>