John Ptacek John Ptacek - 1 year ago 192
Javascript Question

Accessing specific array element in an Angular2 Template

I have an array that I can loop through using

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

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

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....

Answer Source

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}}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download