Home > Software design >  Angular - display default value before result of | async
Angular - display default value before result of | async

Time:07-13

How can I display - until the result of $futureCredit returns?

    <span [innerText]="'-'">
      {{ futureCredit$ | async | currency:'EUR'}}
    </span>

I tried with innerText but the result of the async doesn't override the -.

CodePudding user response:

This should work.

<span>
  {{ (futureCredit$ | async | currency:'EUR') || '-'}}
</span>

CodePudding user response:

you could also use the ngIf else directive.

<span *ngIf="futureCredit$ | async as credit; else default">
 {{ credit  | currency:'EUR' }}
</span>  
<ng-template #default>
<span> - <span>
</ng-template>

it works for this case but if futureCredit would give back a value that is falsy it will still render the else case.

In this case i would use a custom rxjs pipe:

// invokes a callback upon subscription
export function prepare<T>(
  callback: () => void,
): (source: Observable<T>) => Observable<T> {
  return (source: Observable<T>): Observable<T> =>
    defer(() => {
      callback();
      return source;
    });
}

which you could use like :

---------------------------TS-----------------------------

startFutureVal$ = new Subject<boolean>();
futureVal$.pipe(prepare(() => startFutureVal$.next(true))
                   ,tap(() => startFutureVal$.next(false)))

---------------------------HTML---------------------------

<span *ngIf="futureVal$ | async as val"> val </span>
<span *ngIf="startFutureVal$ | async">
  -
</span>

Of course this is all a bit overkill for your use case.

  • Related