如何使用 NGFOR 循环访问作为 Angular 对象数组的属性



角度新手,对不起,如果这是一个愚蠢的问题,或者我解释不当。

我有一个组件,它声明一个名为 satellites 的输入属性,该属性访问卫星类数组。我需要在 ngFor 循环中使用该属性来构建 HTML 表。我没有获取阵列存储的信息,我只是得到这个输出

Name    Type    Operational Orbit Type  Launch Date
[object Object]
[object Object]
[object Object]
[object Object]
[object Object]

这是输入属性

<app-orbit-list [satellites]="sourceList"></app-orbit-list>

及其访问的类

export class AppComponent {
sourceList: Satellite[];
constructor() {
this.sourceList = [
new Satellite("SiriusXM", "Communication", "2009-03-21", "LOW", true),
new Satellite("Cat Scanner", "Imaging", "2012-01-05", "LOW", true),
new Satellite("Weber Grill", "Space Debris", "1996-03-25", "HIGH", false),
new Satellite("GPS 938", "Positioning", "2001-11-01", "HIGH", true),
new Satellite("ISS", "Space Station", "1998-11-20", "LOW", true),
];
}
}

这是我尝试在表中使用的 ngFor 循环

<tr *ngFor="let newRow of satellites ">{{newRow}}</tr>

有关如何完成这项工作的任何信息甚至澄清将不胜感激,谢谢!

你做得几乎是正确的,你的ngFor正在工作,但是当你打印newRow时,你打印的是整个对象而不是属性。

您需要呈现对象的属性,如下所示:

<tr *ngFor="let newRow of satellites ">
<td>{{newRow.name}}</td>
<td>{{newRow.type}}</td>
...
</tr>
<tr *ngFor="let newRow of sourceList">
<td>{{newRow.Name}}</td>
</tr>

查看此博客,它解释了使用 ngFor 创建表

https://medium.com/@mjthakur413/how-to-create-table-in-angular-7-using-ngfor-3c2c0875b955

您将需要使用嵌套的 *ng 像这样,

<tr *ngFor = "let row of exampleAray2">
<td *ngFor = "let column of exampleArray">
{{row[column]}}
</td>
</tr>

使用对象设置数组格式

// headings   
exampleArray = [{name: 'Name', date: 'date'}, { /*your values*/ }];
// values
exampleAray2 = ['name', 'date'];

同样在你的类中,你可以像这样声明你的数组,

export class AppComponent {
// headings   
exampleArray = [{name: 'Name', date: 'date'}, { /*your values*/ }];
// values
exampleAray2 = ['name', 'date'];
constructor() {
// or you can initialize them here
this.exampleArray = [{name: 'Name', date: 'date'}, { /*your values*/ }];
}
}

最新更新