Accessing specific array element in an Angular2 Template

≯℡__Kan透↙ 提交于 2020-01-12 13:00: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....


回答1:


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



回答2:


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>


来源:https://stackoverflow.com/questions/38544503/accessing-specific-array-element-in-an-angular2-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!