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.
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
<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>
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
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');
}
}
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]}}
