简体   繁体   English

访问 Angular2 模板中的特定数组元素

[英]Accessing specific array element in an Angular2 Template

I have an array that I can loop through using ng-for syntax.我有一个可以使用ng-for语法循环的数组。 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 : 2020 编辑:

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

is the new way for the null check是空检查的新方法

Original answer : {{elements[0].name}}原始答案: {{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).如果您异步加载elements (从服务器或类似设备),那么当 Angular 在来自服务器的响应到达之前尝试更新绑定时会失败(通常是这种情况)。 You should get an error message in the browser console though.不过,您应该会在浏览器控制台中收到一条错误消息。

Try instead试试吧

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

Work around, use ngIf check the length.解决方法,使用 ngIf 检查长度。 elements?元素? means if elements is null, don't read the length property.意味着如果元素为空,则不读取长度属性。

<div *ngIf="elements?.length">
    {{elements[0].name}}
</div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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