访问 Angular2 模板中的特定数组元素 [英] Accessing specific array element in an Angular2 Template

查看:24
本文介绍了访问 Angular2 模板中的特定数组元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个可以使用 ng-for 语法循环遍历的数组.但是,最终我只想访问该数组的一个元素.我不知道该怎么做.

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.

在我的组件脚本中

  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>

然而,试图通过使用

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

似乎不起作用.

模板中的格式非常明确,所以我希望能够在模板中明确访问数组的每个元素.

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

是空检查的新方法

原答案:{{elements[0].name}}

Original answer : {{elements[0].name}}

应该可以正常工作.如果你加载 elements 异步(从服务器或类似的),那么当 Angular 在来自服务器的响应到达之前尝试更新绑定时会失败(通常是这种情况).不过,您应该会在浏览器控制台中收到一条错误消息.

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.

试试吧

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

这篇关于访问 Angular2 模板中的特定数组元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆