`
这是用TypeScript编写的代码。
这是构建HTML表的代码,该表显示嵌套对象中的项。这段代码运行得很好,但在打印时存在一个问题,比如它应该只创建包含行的表,但它也打印一些coma,这些coma甚至不属于执行的任何行的一部分
import {Component} from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'Angular';
data = {
id: '0001',
type: 'donut',
name: 'Cake',
ppu: 0.55,
batters: {
batter: [{
id: '1001',
type: 'Regular'
},
{
id: '1002',
type: 'Chocolate'
},
{
id: '1003',
type: 'Blueberry'
},
{
id: '1004',
type: "Devil's Food"
}
]
},
topping: [{
id: '5001',
type: 'None'
},
{
id: '5002',
type: 'Glazed'
},
{
id: '5005',
type: 'Sugar'
},
{
id: '5007',
type: 'Powdered Sugar'
},
{
id: '5006',
type: 'Chocolate with Sprinkles'
},
{
id: '5003',
type: 'Chocolate'
},
{
id: '5004',
type: 'Maple'
}
]
};
//Function which build HTML Table which get's dynamic values.
htmlStr = (data, wrapperClassName, tableClassName = 'table table-sm') => {
return `
<div class=${tableClassName}>
<table className=${tableClassName}>
<tbody>
${Object.keys(data).map( (k) => `
<tr>
${(!Array.isArray(data) && `
<td>${k.replace(/_/g, ' ')}</td>`) || ''} ${ data[k] && typeof data[k] === 'object' ? `
<td>
${this.htmlStr(data[k], wrapperClassName, tableClassName)}
</td>` : `
<td>
<span>${data[k] || ''}</span>
</td>` }
</tr>` )}
</tbody>
</table>
</div>`;
};
}