问题
I have one problem on create table. My struct data is dynamic,that means number of row and column is variable like matrix m*n
. and struct is available on here.
I want to show json (above photo)
to mat-table.but I can't correctly assign data to table and it show Duplicate data on table.show column0
for all rows of mat-table.
while Correct data in table should be
My code is available on stackblitz.
in this code,i want create table with 5
col and 6
row.
how can i solve it and show all data in this table?
回答1:
when you has a matrix you has a FormArray of FormArrays,e.g. If you has a data like
export const data=[['uno','one'],['dos','two'],['tres','three']]
You can format a formArray of FormArray like (**)
myformArray = new FormArray(
data.map(row=>new FormArray(
row.map(x=>new FormControl(x))
)))
When you use a mat table you need a 'displayedColumns', an array with the columns you want display. If you want has a button "delete", you can use another variable more
displayedHeads: string[] = data[0].map((x,index)=>'col'+index);
displayedColumns: string[] = this.displayedHeads.concat('delete')
Well, It's close to be ready, I added a new variable more that indicate the number of columns you has -this allow us add a new row-, and the table using viewChild
columns: number = data[0].length;
@ViewChild(MatTable, { static: true }) table: MatTable<any>;
Our table it's ready to show it:
<button mat-button (click)="add()">Add row</button>
<table mat-table [dataSource]="myformArray.controls" class="mat-elevation-z8">
<!-- Name Column -->
<ng-container *ngFor="let head of displayedHeads;let j=index" [matColumnDef]="head">
<th mat-header-cell *matHeaderCellDef> {{head}} </th>
<td mat-cell *matCellDef="let element">
<input [formControl]="element.at(j)">
</td>
</ng-container>
<ng-container matColumnDef="delete">
<th mat-header-cell *matHeaderCellDef></th>
<td mat-cell *matCellDef="let element;let i=index;">
<button mat-button (click)="delete(i)">delete</button>
</td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
See that the dataSource is myformArray.controls
and in the input is [formControl]="element.at(j)
, yes "element is the inner formArray"
You can see the example in stackblitz (*)
I add two functions to add and remove row
delete(index: number) {
this.myformArray.removeAt(index);
this.table.renderRows()
}
add() {
const empty = [];
for (let i = 0; i < this.columns; i++)
empty.push(true)
this.myformArray.push(
new FormArray(empty.map(x => new FormControl('')))
)
this.table.renderRows()
}
(*) In the stackblitz I added a directive to allow move across cells using arrows keys
(**) In your case you format the form Array as
myformArray = new FormArray(
data.map(row=>new FormArray(
row.map(x=>new FormControl(x.c))
)))
来源:https://stackoverflow.com/questions/59223972/create-dynamic-mat-table-like-math-matrix-with-angular-material