首页 > 解决方案 > 如何使用 ngFor 在表格中显示对象数组?

问题描述

我正在尝试显示我在表格中收集的一些结果。我知道使用ngFor,或者至少这是我的研究向我展示的。

我尝试使用keyvalue其他帖子中提到的方法,但这仍然没有呈现任何结果。我认为这是一个超级简单的问题,我只是缺少一个小组件。

所以我创建了一个[Object Array]看起来userResults

[
{key: 'example@example.com', value: 'message'}
]

它是在我的结果组件中创建的,看起来像:

@Component(
{
    selector: 'app-results',
    templateUrl: './results.component.html',
    styleUrls: ['./results.component.css'],
    providers: [ApiService, DataService]
})
export class ResultsComponent implements OnInit
{
    constructor(private _apiService: ApiService, private router: Router, private _dataService: DataService)
    {
        this.userResults = this._dataService.getData();
    }
displayedColumns: string[] = ['User Email', 'Result'];
userResults = [];
employeeCheck(user: string)
    {
        console.log('Completing employee check')

        if (this)
        { 
            this.userResults.push({
                key: user,
                value:  this.messages[3];
            });
            this.createTable();
        }
        else if (this)
        { //Check that NGP exists and is valid
            this.userResults.push({
                key: user,
                value:  this.messages[4];
            });
            this.createTable();
        }
        else if (this)
        { 
            this.userResults.push({
                key: user,
                value:  this.messages[6]
            });
            this.createTable();
        }

        else if (this)
        { 
            this.userResults.push({
                key: user,
                value:  this.messages[5]
            });
            this.createTable();
        }
        else
        { //Don't know what else to do
            this.userResults.push({
                key: user,
                value:  this.messages[7]
            });
            console.log(this.userResults[0].key)
            this._dataService.saveResults(this.userResults);
            this.createTable();
        }
//console.log(this.userResults);

    }


    userCheck(user: string)
    {
        console.log('Checking ', user, ' information.');

        if (this)
        {
            this.userResults.push({
                key: user,
                value:  this.messages[0]
            });
            this.createTable();
        }
        else if (this)
        {
            this.userResults.push({
                key: user,
                value:  this.messages[1]
            });
            this.createTable();
        }
        else if (this)
        {
            this.userResults.push({
                key: user,
                value:  this.messages[2];
            });
            this.createTable();
        }
        else
        {
            this.employeeCheck(user);
        }
    }
createTable()
    {
        console.log(this.userResults)
        console.log('going to results')
        this.router.navigate(['/results'])      
    }

我的服务看起来像:

import { Injectable } from '@angular/core';
import { Observable, Subject, throwError} from 'rxjs';

@Injectable({ providedIn: "root" })
export class DataService {
    private results: any[];
    constructor() { }

    saveResults(someArray){
        console.log('saving results')
        this.results = someArray
        console.log(this.results)
    }


}

我通过在不同的函数中执行一系列 if/else 语句来创建这个对象,根据需要向 objct 添加值。在该函数结束时,我导航到该/results页面,该页面的 html 如下所示:

<div class="container" style="text-align:center">
  <br />
  <h1>Results</h1>

  <head>
    <style>
      table,
      th,
      td {
        border: 1px solid black;
        align: center;
      }
    </style>
  </head>
  <body>
    <table style="width:50%" align="center">
      <tr>
        <th *ngFor="let col of displayedColumns">
          {{ col }}
        </th>
      </tr>
      <tr *ngFor="let item of userResults | keyvalue">
        <td>{{ item.key }}</td>
        <td>{{ item.value }}</td>
      </tr>

      <tr></tr>
    </table>
  </body>

我想得到一张看起来像的桌子

|       User Email       |       Result       |
|  example@example.com   |       message      |

截至目前,我只显示要显示的列名。就像我之前说的,我已经提到了关于这个主题的其他帖子。我正在遵循那里提到的建议,但它仍然无法正常工作。我想有一个小而关键的部分我忘记了。任何帮助,将不胜感激。谢谢

标签: htmlangular6ngfor

解决方案


keyvalue管道用于迭代对象而不是数组。迭代数组*ngFor不需要任何额外的结构。

<tr *ngFor="let item of userResults">
  <td>{{ item.key }}</td>
  <td>{{ item.value }}</td>
</tr>

应该够了,哪里userResults和这个差不多

userResults = [
  {key:"example1@example.com", value: "message1"},
  {key:"example2@example.com", value: "message2"}
]

还有一件事是;head body并且style标签不应该在角度模板中使用。并且您应该将样式作为内联样式css放在component.ts文件中

@Component({
  selector: "app-my",
  templateUrl: "./my.component.html",
  styles: [
    `
      table,
      th,
      td {
        border: 1px solid black;
        align: center;
      }
    `
  ]
})
export class MyComponent {}

或在一个单独的文件中调用component.css并添加该文件应在您的 component.ts 文件中引用

@Component({
  selector: "app-my",
  templateUrl: "./my.component.html",
  styleUrls: ["./my.component.css"]
})
export class MyComponent {}

推荐阅读