9

How to access the first item of an array when using async pipe?

<nav-tabs
   [tabs]="(pageTabs$ | async)"
   [activeTab]="(pageTabs$ | async)[0]">
</nav-tabs>

I've tried (pageTabs$ | async)[0] but it didn't work.

1
  • 1
    Actually, this is how it is done. But actually, this smells, because pageTabs$ is subscribed twice. Commented Mar 5, 2017 at 21:36

4 Answers 4

11

Found an even easier way of doing it (without creating a custom pipe): add a map to the observable.

component.ts

this.activeTab$ = this.pageTabs$.map(x => x[0]);

component.html

<nav-tabs
   [tabs]="(pageTabs$ | async)"
   [activeTab]="(activeTab$ | async)">
</nav-tabs>
Sign up to request clarification or add additional context in comments.

Comments

2

A simpler way it's to assign it to a template value with the as statement

<nav-tabs
   [tabs]="(pageTabs$ | async as pageTabs)"
   [activeTab]="pageTabs[0]">
</nav-tabs>

Comments

1

I would just write a new getter in your components code:

 public get activeTab$() {
   return this.pageTabs$.map(tabs => Array.isArray(tabs)? tabs[0]: null;
 }

and then use it:

 [active-tab]="activeTab$ | async"

Or you can do it in your nav-tabs component:

 public get activeTab() {
    return Array.isArray(this.tabs)? tabs[0]: null;
 }

Comments

0

You have to create custom pipe which will take first item from array, (pageTabs$ | async) is not an array.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.