Skip to content Skip to sidebar Skip to footer

Accessing Specific Array Element In An Angular2 Template

I have an array that I can loop through using ng-for syntax. However, ultimately I want to access just a single element of that array. I cannot figure out how to do that. In my com

Solution 1:

2020 Edit :

{{elements?.[0].name}} 

is the new way for the null check

Original answer : {{elements[0].name}}

should just work. If you load elements async (from a server or similar) then Angular fails when it tries to update the binding before the response from the server arrived (which is usually the case). You should get an error message in the browser console though.

Try instead

{{elements && elements[0].name}}

Solution 2:

Work around, use ngIf check the length. elements? means if elements is null, don't read the length property.

<div *ngIf="elements?.length">
    {{elements[0].name}}
</div>

Post a Comment for "Accessing Specific Array Element In An Angular2 Template"