Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 component script I have

  export class TableComponent {

    elements: IElement[];

}

In my template, I am able to loop through the elements via

<ul>
<li *ngFor='let element of elements'>{{element.name}}</li>
</ul>

However, trying to access an item in the element array by secifically referencing an item utilizing

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

does not seem to work.

The formatting in the template is pretty explicit, so I want to be able to access each element of the array explicitly in the template.

I am not understanding something basic....

like image 605
John Ptacek Avatar asked Jul 23 '16 17:07

John Ptacek


2 Answers

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}}
like image 180
Günter Zöchbauer Avatar answered Oct 17 '22 00:10

Günter Zöchbauer


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>
like image 26
Chybie Avatar answered Oct 17 '22 01:10

Chybie