Html ngFor - 按索引打印数组项
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38133688/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ngFor - printing an array item by index
提问by Roka545
I have an ngFor loop that loops through a list of objects (called configs) and prints data for each object.
我有一个 ngFor 循环,它循环遍历对象列表(称为配置)并打印每个对象的数据。
I also have an array in my TypeScript file that I would like to print as well. The array has the same length as the 'configs' list (and will always have the same length). Here's my HTML file's ngFor:
我的 TypeScript 文件中还有一个数组,我也想打印它。该数组的长度与 'configs' 列表的长度相同(并且始终具有相同的长度)。这是我的 HTML 文件的 ngFor:
<button *ngFor="let config of configs; let i = index" type="button" style="text-align:left; margin-right: 10px; margin-bottom: 10px" class="btn btn-primary">
Name: {{config.name}} <br /> Op Point: //Op Point ARRAY OBJECT HERE BASED ON INDEX// <br />
</button>
I've placed "//Op Point ARRAY OBJECT HERE BASED ON INDEX//" in the code snippet above to point out where I want to print values from an array. The array in my TypeScript file is a 1x4 2D array named configOpPoints.
我在上面的代码片段中放置了“//Op Point ARRAY OBJECT HERE BASED ON INDEX//”,以指出我想从数组中打印值的位置。我的 TypeScript 文件中的数组是一个名为 configOpPoints 的 1x4 2D 数组。
Basically, how can I print data in my existing ngFor from the configOpPoints array? I tried 'configOpPoints[i]' but that didn't work.
基本上,如何从 configOpPoints 数组打印现有 ngFor 中的数据?我试过 'configOpPoints[i]' 但这没有用。
回答by Gabi
I'm not sure if this is what you are after:
我不确定这是否是您所追求的:
import { Component } from '@angular/core';
export class Config {
name:string;
}
@Component({
selector: 'my-app',
template: `
<h1>Angular 2 App - Test ngFor</h1>
<button *ngFor="let config of configs; let i = index" type="button" style="text-align:left; margin-right: 10px; margin-bottom: 10px" class="btn btn-primary">
Name: {{config.name}} <br /> {{configOpPoints[i]}} <br />
</button>
`
})
export class AppComponent {
configs:Config = [
{name: 'config1'},
{name: 'config2'},
{name: 'config3'}
];
configOpPoints:Array = [
[ 1, [ 'op1', 'OP1', 12, 23] ],
[ 2, [ 'op2', 'OP2', 32, 43] ],
[ 3, [ 'op3', 'OP3', 52, 63] ]
];
}
check this plnkr for a running version : http://plnkr.co/edit/m5RhEElElHj0pVTPx5Tc?p=preview
检查此 plnkr 的运行版本:http://plnkr.co/edit/m5RhEElElHj0pVTPx5Tc?p=preview