I need to dynamically create table of object in angular 2/typescript
Create array of objects
export class AppComponent {
gameBoard= GAMEBOARD;
}
var size=10;//will be for user enter
var GAMEBOARD=[];
var x=0;
for(var i=0;i<size;i++){
for (var j=0; j < size; j++) {
if (!GAMEBOARD[i]) {
GAMEBOARD[i] = [];
}
GAMEBOARD[i][j]=new GameField(x);
x++;
}}
Use in template:
<tr *ngFor="let x of gameBoard">
<game-field *ngFor="let field of gameBoard[x]" [field]="field" ></game-field>
</tr>
Try to input:
@Component({
selector: 'game-field',
// inputs:['field'],
template: '<td >{{field.id}}</td>',
styleUrls: ['./app.component.css']
})
export class GameFieldComponent{
@Input() field: GameField;
}
How to put all object from GAMEBOARD into table?
(I'm a newbie in web development and Stackoverflow so please for indulgence)
As you place custom-element inside tr tag, it would become invalid html and it will thrown of from table tag. You can only place td, th,etc(only table element in tr) all the other element/ custom element aren't allowed in tr
Rather you should make repeat td and generate content from game-field component. It could look something like below.
Also correct inner ngFor to directive loop over x instead of gameBoard[x]
<tr *ngFor="let x of gameBoard">
<td *ngFor="let field of x">
<game-field [field]="field"></game-field>
</td>
</tr>
game-field component Template
template: '{{field.id}}',
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With