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?

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

When I use (state$ | async) as state, will state variable be available in the entire template? What about visibility?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.