6

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?

3 Answers 3

5

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.

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

Comments

3

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

1 Comment

Nice idea :) Shouldn't then this also work {{ (chapters?.first() | async)?.title }}. Never tried operators that need to be imported in bindings.
1

? (safe-navigation) only works with . (dereference operator) not with [] (index access operator)

What might work is

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

but I'm not sure if chapters is subscribed to twice. In this case this wouldn't be a good solution. Angular2 does some deduplication in template bindings but not sure about | async.

Another approach would be to assign the result to a property

ngOnInit() {
  this.chapters.subscribe(val => this.captersResult = val);
}
<h1>{{(chaptersResult?.length && chaptersResult[0].title}}</h1>

}

Comments

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.