Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing element in async array

I have an angularjs2 app that receives a list of jsons from my firebase service. I want to access and display the first element of the list.

Here is what I have tried

<h1>{{(chapters | async)?[0].title}}</h1>

which gives me a Template parse error.

How do I access the first element of an async array?

like image 335
agsolid Avatar asked Nov 16 '16 06:11

agsolid


2 Answers

I would do it like this:

<h1>{{((chapters | async) || [])[0]?.title}}</h1>

It's a more generic solution, works for any index, not only first.

like image 115
Andrei Cojea Avatar answered Sep 19 '22 11:09

Andrei Cojea


You can use pipe like this:

@Pipe({
  name: 'first'
})
export class First {
  transform(val, args) {
    if (val === null) return val;
    return val[0];
  }
}

and in your html

<h1>{{ (chapters | async | first)?.title }}</h1>

Plunker Example

like image 27
yurzui Avatar answered Sep 22 '22 11:09

yurzui