内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用
我在使用服务从Angular类格式化我的表时遇到了问题。
我的表显示,但它们包含每个单元格之间的逗号(,)。
在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
这是因为你正在迭代对象数组。
尝试将对象转换为数组。
在组件中:
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>