Access to a specific array element in an Angular2 template

I have an array that I can execute using ng-for syntax. However, in the end I want to access one element of this array. I can’t figure out how to do this.

In my script component, I have

  export class TableComponent { elements: IElement[]; } 

In my template, I can scroll through elements

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

However, trying to access an element in an array of elements, with a link to an element using

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

doesn't seem to work.

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

I do not understand something basic ....

+8
javascript angular angular2-template
source share
2 answers
 {{elements[0].name}} 

must work. If you download elements async (from a server or similar), then Angular fails when it tries to update the binding before a response is received from the server (which usually happens). However, you should receive an error message in the browser console.

Try instead

 {{elements && elements[0].name}} 
+14
source share

Work, use ngIf to check the length. Elements? means that if the elements are null, do not read the length property.

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

All Articles