1

My component has an Observable named state$: how can I avoid repeat myself when I need to access state$.favorites, like the example below?

@Component({
  selector: 'app-example',
  template: `
    <ng-container *ngIf="(state$ | async).favorites.length">
      {{ (state$ | async).favorites.length }}
    </ng-container>
  `,
})
export class ExampleComponent() {
  @Select(state => state.app) state$: Observable<AppState>;
}

Is there any way to assign it to a template variable?

gremo
  • 48,580
  • 70
  • 242
  • 401

1 Answers1

3

You can do the following:

 <ng-container *ngIf="(state$ | async) as state">
      {{ state.favorites.length }}
  </ng-container>

You don't need to check for .length. By doing what I did, you are checking if the observable has arrived and checking if the value is not null.

Patricio Vargas
  • 4,625
  • 8
  • 38
  • 80
  • 3
    When I use `(state$ | async) as state`, will `state` variable be available in the entire template? What about visibility? – gremo Sep 20 '18 at 09:32