Handling Multiple Observables in @if

1 분 소요

Plan

  1. Define a single Observable within ngIf or @if.
  2. Define multiple Observables within ngIf or @if.

Applying a Single Observable

To utilize the async pipe, append it to the variable name and define a variable name to use with as. This allows direct access to the resolved value of the Observable within the template.

<!-- control flow -->
@if (user$ | async; as user) {
  <div>
    <p></p>
  </div>
}
<!-- ngif -->

<div *ngIf="user$ | async as user">
  <p>{{user.name}}</p>
</div>

Applying Multiple Observables

Defining multiple Observables in @if or ngIf in the same manner as a single Observable will result in an error. This is due to the template parser’s inability to correctly handle the combined asynchronous operations directly within the @if or *ngIf directive.

<!-- control flow -->
@if ((user$ | async; as user) || (item$ | async; as item)) {
  <!-- This syntax is not valid -->
}
<!-- ngif -->

<!-- error -->
<div *ngIf="(user$ | async as user) || (item$ | async as item)"></div>

Solution - Applying Multiple Observables

To work with multiple Observables effectively, transform them into an object. This approach allows the @if or *ngIf directive to manage the asynchronous subscriptions properly. The code below demonstrates the correct implementation and will execute without errors. This encapsulates multiple Observables into a single object that can be evaluated.

<!-- control flow -->
@if ({ user: user$ | async, item: item$ | async }; as data) {
  <div>
    @if (data.user; as user) {
      <p>User Name: </p>
    }

    @if (data.item; as item) {
      <p>Item Name: </p>
    }
  </div>
}
<!-- ngif -->

<div *ngIf="{user: user$ | async, item: item$ | async} as data">
	<p>{{data.user.name}}</p>
  <p>{{data.item.name}}</p>
</div>

Reference Site

댓글남기기