在Angular 2中将列和数据动态加载到表中 [英] Dynamically loading columns and data in to table in Angular 2
问题描述
我有一个要在其中创建表的HTML页面.该表中的列是动态的,这意味着使用any[]
类型将它们从服务器中提取到组件中的变量中.该表中的数据也是动态的,这意味着在编程时,我不知道将要绑定到表中的列和数据.
I have an HTML page in which I want to create a table. The columns in this table are dynamic which means that they are fetched from the server into a variable in the component using any[]
type. The data in this table is also dynamic which means that at the time of programming I don't know which columns and data will come to get bound in the table.
我尝试了下面的代码,但它似乎无法正常工作或出现任何错误.它只是在tbody
中创建空的td
.
I have tried below code but it doesn't seem to work or give any error. It just creates empty td
in the tbody
.
Expense.component.html
Expense.component.html
<div class="panel panel-default" style="margin-top:10px;">
<div class="panel-heading">
Expenses
</div>
<div class="panel-body" style="position:relative">
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th *ngFor="#column of columns">
{{column}}
</th>
</tr>
</thead>
<tbody>
<tr *ngFor="#data of data">
<td *ngFor="#column of columns">
{{data.column}}
</td>
</tr>
</tbody>
</table>
</div>
</div>
在上面的代码中,成功创建了列,但是数据和列mashup无法正常工作.我确信Angular 2中一定有一种方法可以实现这一目标.
In the above code, the columns are getting created successfully but the data and column mashup is not working. I am sure there must be a way in Angular 2 to achieve this.
Expense.component.ts
Expense.component.ts
export class ExpenseComponent implements OnInit {
errorMessage: any[];
columns: string[];
data: any[];
constructor(private _commonService: CommonService, private _expenseService: ExpenseService) {
}
ngOnInit(): void {
this._commonService.getColumnNames('condomanagement', 'expenses')
.subscribe(data => this.promise(data), error => this.errorMessage = <any>error);
}
private promise(data: string[]) {
this.columns = data;
this._expenseService.getExpenses('condomanagement', this.columns)
.subscribe(data => this.anotherPromise(data), error => this.errorMessage = <any>error);
}
private anotherPromise(data: any[]) {
this.data = data;
console.log(this.columns);
console.log(this.data);
}
private handleError(error: Response) {
console.error(error);
return Observable.throw(error.json().error || 'Server error');
}
}
数据已按照上面的代码登录到控制台,但根据我的试用,它无法在HTML中工作.有什么想法吗?
The data is getting logged in to console in the above code but not working in the HTML as per my trial. Any ideas, please?
已更新:只是像这样使用插值,就可以了
Updated: Just used interpolation like this and it worked
{{mydata[column]}}
推荐答案
代替使用
<tr *ngFor="#data of data">
您应该使用
<tr *ngFor="#data of data" *ngModel="data[column]">
这篇关于在Angular 2中将列和数据动态加载到表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!