我正在使用Angular 4/5,我必须根据字符串值在Angular中创建几个表。这是我创建表格的模型。
class NameValuePair {
Name: string;
Value: string;
}
export class Family {
Properties: Array<NameValuePair>;
PropertyType: string;
}
下面给出了表格中包含的硬编码值。
export const list1: Family[] =
[
{
Properties: [
{
Name: "A",
Value: "1"
},
{
Name: "B",
Value: "2"
},
{
Name: "C",
Value: "3"
}
],
PropertyType: "Type 1"
},
{
Properties: [
{
Name: "A",
Value: "10"
},
{
Name: "B",
Value: "20"
},
{
Name: "C",
Value: "30"
}
],
PropertyType: "Type 1"
},
{
Properties: [
{
Name: "A",
Value: "100"
},
{
Name: "B",
Value: "200"
},
{
Name: "C",
Value: "300"
}
],
PropertyType: "Type 2"
}
]
现在,要注意的主要事项是将根据PropertyType创建表。如在上面的结构中,数组的前两个元素的PropertyType是相同的,即类型1 ,因此将创建2个表。一个带有标题/标题:输入1 ,另一个带标题:输入2。 第二个数组元素的properties []数组将成为第一个表的第二行。我无法找到有关如何基于此PropertyType字符串值创建表的逻辑。但是,这是我在component.html文件中写的,但这个逻辑是不正确的。
<div class="container pt-4" *ngFor="let element of list;let i = index">
<ng-container *ngIf="list[i].PropertyType == list[i+1].PropertyType">
<div style="padding-left:250px;font-size: 20px" class="pb-2">{{element.PropertyType}}</div>
<table id="{{element.PropertyType}}" class="table table-striped table-bordered table-responsive pb-3 mx-auto">
<thead style="height:40px">
<tr align="center">
<th *ngFor="let property of element.Properties" style="font-size: 20px">{{property.Name}}</th>
</tr>
</thead>
<ng-container *ngFor="let element1 of list">
<tr align="center" *ngIf="element.PropertyType == element1.PropertyType">
<td *ngFor="let property of element1.Properties; let propertyIndex = index" style="width: 200px">
<ng-container [ngSwitch]="propertyIndex">
<div *ngSwitchDefault style="font-size: 20px">{{property.Value}}</div>
</ng-container>
</td>
</tr>
</ng-container>
</table>
</ng-container>
</div>
list 这里指的是如上所述的list1 const数组。请帮忙。
答案 0 :(得分:1)
这是完整的逻辑,我没有添加css,因为没有问。使用此功能https://stackblitz.com/edit/angular-hd9jey
'/usr/bin/ruby /path/to/migrate.rb'
import {
Component
} from '@angular/core';
import {
list1
} from './list1';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
})
export class AppComponent {
tableArray = [];
constructor() {
let tableObject = {};
list1.forEach(i => {
if (tableObject[i.PropertyType]) {
tableObject[i.PropertyType].push(i);
} else {
tableObject[i.PropertyType] = [i];
}
this.tableArray = Object.entries(tableObject);
});
}
}
答案 1 :(得分:0)
您希望首先将list1数据操作为更好的格式: e.g。
export interface CustomTable {
header: string,
rows: Properties[]
}
const tables: CustomTable[] [];
list1.forEach(family => {
// Check if this type is already in the table.
const myTable: CustomTable = tables.find(customTable => customTable.header === family.propertyType);
if (myTable) {
// If it is, then add a new row
myTable.rows.push(family.Properties);
} else {
// If not, create a new table
myTable.rows.push({
header: family.propertyType,
rows: [family.Properties]
});
}
});
然后相应地更改你的HTML。你可能想要
<ng-container ngFor="let table of tables">
并且在那个地方a:
<tr *ngFor=let row of tables.rows>