如何使用 ngfor 遍历 属性 中的对象数组 angular

how to use ngfor to loop over a property that is an array of objects in angular

angular 的新手,如果这是一个愚蠢的问题或我解释不当,请见谅。

我有一个组件声明了一个名为 satellites 的输入 属性,它访问 Satellite class 数组。我需要在 ngFor 循环中使用 属性 来构建 HTML table。我没有得到数组存储的信息,而是得到了这个输出

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>

和它访问的class

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),
    ];
 }
}

这是我试图在 table

中使用的 ngFor 循环
   <tr *ngFor="let newRow of satellites ">{{newRow}}</tr>

任何关于如何使这项工作甚至澄清的信息都将不胜感激,谢谢!

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

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

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

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

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

创建 table

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

你需要像这样使用嵌套的 *ngFor,

<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'];

同样在您的 class 中,您可以像这样声明数组,

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*/ }];
  }
}