Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access first item of array using async pipe in Angular 2

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.

like image 915
AndreFeijo Avatar asked Mar 05 '17 21:03

AndreFeijo


2 Answers

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>
like image 158
AndreFeijo Avatar answered Sep 21 '22 07:09

AndreFeijo


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;
 }
like image 43
cyr_x Avatar answered Sep 19 '22 07:09

cyr_x