18

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

2 Answers 2

30

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}}
Sign up to request clarification or add additional context in comments.

3 Comments

This was exactly the issue. Async call and the data was not initialized on load. This is a bit different behavior than Angular 1.x. Thanks!
@RamiAlloush what Dart/Flutter version?
Hi @GünterZöchbauer, I thought we were talking about Angular :D. I'm running Angular v9. I just want to do elements?.[0] but I can't. Thanks
7

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.