扩展 Jeremy 的答案,您可以实施
import { Component } from "@angular/core";
export class Table {
constructor(
public title: string,
public columns: string[],
public rows: Row[]
) {}
}
export class Row {
constructor(public cells: Cell[]) {}
}
export type CellValue = string | number | boolean;
export class Cell {
constructor(public value: CellValue) {}
isText(): boolean {
return typeof this.value === "string";
}
isNumber(): boolean {
return typeof this.value === "number";
}
isBoolean(): boolean {
return typeof this.value === "boolean";
}
}
@Component({
selector: "app-root",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent {
title = "CodeSandbox";
table: Table;
constructor() {
this.table = new Table(
"Table name",
["Country", "State", "Population", "Northern"],
[
new Row([new Cell("AR"), new Cell("BSAS"), new Cell(44490000), new Cell(false)]),
new Row([new Cell("US"), new Cell("CA"), new Cell(328000000), new Cell(true)])
]
);
}
}
并让模板类似于以下内容:
<table>
<tr>
<th *ngFor="let col of table.columns">{{col}}</th>
</tr>
<tr *ngFor="let row of table.rows">
<td *ngFor="let cell of row.cells">
<input type="text" *ngIf="cell.isText()" [(ngModel)]="cell.value" />
<input type="number" *ngIf="cell.isNumber()" [(ngModel)]="cell.value" />
<input
type="checkbox"
*ngIf="cell.isBoolean()"
[(ngModel)]="cell.value"
/>
</td>
</tr>
</table>
由于[(ngModel)],这些值将在您编写输入时自动填充。希望它可以帮助你。我创建了一个示例here,以防您需要此代码。