2

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
  • 47,186
  • 75
  • 257
  • 421

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
  • 5,236
  • 11
  • 49
  • 100
  • 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