askeet
askeet

Reputation: 719

Optional Async Pipe Or Default

I didn't find the better way how to read default value if observable value is undefined.
Instead of writing this part of code for each observable property within template

            <div *ngIf="!property.visible$
              ? property.visible || true
              : (property.visible$ | async">Test</div>

Can be here the shortest way to do it?

Currently am looking for possibility writing a customPipe to do the same work but seems like it's really difficult to extend an async Pipe for the purpose to have this template

property.visible$ | async: property.visible || true 

Or may you have other ideas ?

Note:

Also it's possible to write a function with this logic in the ts file but don't think it will be a good idea for performance to take(1) subscribe value each time while html is updated and we need to read an observable value

Upvotes: 3

Views: 4832

Answers (3)

Ishan Fernando
Ishan Fernando

Reputation: 2858

I think you can wrap the command in the bracket and add a default like below

(property.visible$ | async) || true

Upvotes: 4

askeet
askeet

Reputation: 719

It's possible to use this extension async pipe

import { Pipe, PipeTransform } from '@angular/core';
import { Observable, of } from 'rxjs';

@Pipe({ name: 'default$' })
export class Default$Pipe implements PipeTransform {
  transform(
    value$: Observable<any> | undefined,
    defaultValue: any
  ): Observable<any> {
    return value$ ? value$ : of(defaultValue);
  }
} 

 property.visible$| default$ : property.visible || false | async  

Upvotes: 3

nickbullock
nickbullock

Reputation: 6599

You can create your own observable and then susbscribe to it with async pipe:

this.visible$ = of({}).pipe(switchMap(() => {
 if (this.property.visible$) return this.property.visible$;

 return of(this.property.visible);
}));

...

<div *ngIf="visible$ | async"></div>

Please take a look at this stackblitz

Upvotes: 4

Related Questions