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

查看:91
本文介绍了访问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

{{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天全站免登陆