Miguel Moura
Miguel Moura

Reputation: 39364

Render a Observable object property in Angular template

I have the following Angular 7 component:

export class PostComponent implements OnInit {

  post$: Observable<PostModel>;

  constructor(private postService: PostService) { }

  ngOnInit() {

    this.post$ = postService.getPostById(25);

  }

}

On the component template I used the following:

<p>Title: {{post$.title}}</p>

Title shows empty and I think is because post$ is an Observable.

When using arrays, e.g. posts$: Observable<PostModel[]> I pass the observable to the template and it works fine using ngFor.

But how should I do it in this case?

Observable with an Array

When using an Observable of an array I have the following in the HTML template:

<div *ngIf="(posts$ | async)?.length > 0; else loading">
  <ng-container *ngFor="let post of posts$ | async">
    {{post.title}}
  </ng-container>
</div>
<ng-template #loading>
  Loading ...
</ng-template>

This allows me to show a loading message while loading.

Upvotes: 6

Views: 6710

Answers (1)

Nikos Tsokos
Nikos Tsokos

Reputation: 3356

You will have to use the async pipe as:

<p>Title: {{(post$ | async).title}}</p>

Upvotes: 12

Related Questions