简体   繁体   中英

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

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

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM