首页 > 解决方案 > Angular 5 - 表格格式错误(html页面)

问题描述

预先感谢您的帮助。

我无法使用服务从角度类格式化我的表格。

我的表格显示,但它们在每个单元格之间包含逗号 (,)。我想搭车。

在 HTML 中

<table>
   <thead>
      <tr>
        <th>Period</th>
        <th *ngFor="let m of types.Testing">
          {{m.colors}}
        </th>
      </tr>
    </thead>
    <tbody>
      <th></th>
    </tbody>
</table>

零件

import { Component } from '@angular/core';
import {Mytypes} from './model';
import { myserv } from './shared.service';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
    name = 'Angular 6';

    public types: Mytypes;

    constructor(public _service: myserv) {}

    ngOnInit() {
      this.types = this._service.GetData(true);
    }
}

服务文件

import { Injectable } from '@angular/core';
import {Mytypes, types} from './model';

@Injectable()

export class myserv{

  //sourc - not currently in use
  GetData(sourc: boolean): Mytypes{

    var view = new Mytypes();

    var main = new types();
    main.tests= [
      "--"
    ];
    main.colors= [
      "Blue" , "Red" , "Yellow"
    ];

    view.Testing = [
      main 
    ]

    return view;
}

  constructor() { }
}

模型

import { Injectable } from '@angular/core';

@Injectable()
export class types{

  public tests: Array<string>;
  public colors: Array<string>;

  constructor() { }
}

@Injectable()
export class Mytypes{

  public Testing: Array<types>;
  constructor() { }
}

这当前显示为:

Blue,Red,Yellow

预计显示为:

Blue   Red   Yellow

问题在: https ://stackblitz.com/edit/angular-zdame7?file=src%2Fapp%2Fapp.component.ts

标签: angular

解决方案


那是因为您正在迭代对象数组。

尝试将对象转换为数组。

在组件.ts

 this.mapped = Object.keys(this.types.Testing[0].colors).map(key => ({type: key, value: this.types.Testing[0].colors[key]}));
      console.log(this.mapped);

在你的 html

 <table>
      <thead>
              <tr>
                <th>Period</th>
                <th *ngFor="let m of this.mapped">
                  {{m.value}}
                </th>
              </tr>
            </thead>
            <tbody>
              <th></th>
            </tbody>
      </table>

推荐阅读