我想根据模板中的thead
自动生成th
和td
:
<Datatable>
<tr #lineSelected *ngFor="let subscription of results">
<td nameColumn="Nom">{{subscription.name}}</td>
<td nameColumn="Statut">{{subscription.status}}</td>
<td nameColumn="Origine">{{subscription.origin}}</td>
<td nameColumn="Date d'ajout">{{subscription.date}}</td>
</tr>
</Datatable>
现在:
<table>
<tbody>
<tr>
<td>name1</td>
<td>status1</td>
<td>origin1</td>
<td>date1</td>
</tr
<tr>
<td>name2</td>
<td>status2</td>
<td>origin2</td>
<td>date2</td>
</tr>
</tbody>
</table>
目标:
<table>
<thead>
<th>Nom</th>
<th>Statut</th>
<th>Origine</th>
<th>Date d'ajout</th>
</thead>
<tbody>
<tr>
<td>name1</td>
<td>status1</td>
<td>origin1</td>
<td>date1</td>
</tr
<tr>
<td>name2</td>
<td>status2</td>
<td>origin2</td>
<td>date2</td>
</tr>
</tbody>
</table>
这是我的component.ts
@Component({
selector: 'Datatable',
template: `
<table>
<ng-content></ng-content>
</table>
`,
styleUrls: ['./datatable.component.css']
})
export class DatatableComponent {
}
我该怎么办呢?
答案 0 :(得分:0)
您的DataTable
组件仍有改进空间,但我可以稍后再讨论。
但是,为了实现您的特定用例,您可以做的一件事是:
<强>一些-consumer.component.ts 强>
这将是您使用DataTable
组件的组件。
@Component({
selector: 'ConsumerComponent',
template: `
<Datatable>
<tr>
<th *ngFor="let header of headers">{{ header }}</th>
</tr>
<tr #lineSelected *ngFor="let subscription of results">
<td nameColumn="Nom">{{subscription.name}}</td>
<td nameColumn="Statut">{{subscription.status}}</td>
<td nameColumn="Origine">{{subscription.origin}}</td>
<td nameColumn="Date d'ajout">{{subscription.date}}</td>
</tr>
</Datatable>
`,
})
export class ConsumerComponent implements OnInit {
public results = [{
name: 'foo',
status: 'none',
origin: 'qux',
date: 'some-date-string'
}, {
name: 'baz',
status: 'nil',
origin: 'nil',
date: 'some-date'
}];
public headers = [] as string[];
ngOnInit() {
// If your result array comes from a service, you should have a check first.
this.headers = Object.keys(this.results[0]);
}
}
当然还有其他方法可以做到。