tyskocz
tyskocz

Reputation: 133

Dynamically create table of object in Angular 2

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)

Upvotes: 3

Views: 3856

Answers (2)

Pankaj Parkar
Pankaj Parkar

Reputation: 136144

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}}',

Upvotes: 2

user2697852
user2697852

Reputation:

The problem is that you have the export at the top and you redefine the GAMEBOARD after that. You should move the

var GAMEBOARD = [];

To the top.

Also, using const and let, instead of var would help you avoid these problems.

Upvotes: 0

Related Questions