Abgehter Abgehter - 18 days ago 5
TypeScript Question

Angular 2 place components depending on an array

im new to angular 2 and i got stuck...
I try to create a board for a boardgame (reversi, board like chess but mono-color)
I have a class cellInfo(here i want to hold the infos)

constructor(row: number, col: number, stats: boolean[]){
this.row = row;
this.col = col;
this.stats = stats;
}


I have a class courtInfo(here i create an array of cellinfo)

constructor(x: number){
this.x = x;
this.cells = new CellInfo[x];

for(let row: number = 0; row < x; row++){
this.cells[row] = new CellInfo[x];
for(let col: number = 0; col < x; col++){
this.cells[row][col] = new CellInfo(row, col, [false, false, false])
}
}
}


I have a component courtComonent


  • in the .ts i create a courtInfo

    constructor() {this.round = new CourtInfo(8); }



(I named round cause later i want to refresh this array each round)


  • in the html i tryed to create a component-object from class cellComponent

    div *ngFor="let cellrow of round.cells"

    div class = row; *ngFor="let cellcol of round.cells[cellrow]"

    div class = col

    cell></cell

    /div

    /div

    /div



(please imagine the < and >

in the court.component.css i have this:

.row{
--row-hight: 12,5%;
display: table;
width: 100%;
height: var(--row-hight);
}
.col{
display: flex;
width: auto;
height: 100%;
}
cell{
display: flex;
width: 100%;
height: 100%;
}


the CellComponent itself shell be a div wich shell (later) draw a circle or not.

But atm this is not working, the cells are not added to the court.
I dont know if i had to bind somewhere, i guessed that not cause the array [cells] is a class-intern...

Im seeking for some hints

Answer

The way you construct the cell info doesn't make much sense. You are making both the rows and their values have the type of CellInfo, there are no arrays anywhere.

It should be more like this:

constructor(x: number){
  this.x = x;
  this.cells = []; // the type of cells should be CellInfo[][]

  for(let row: number = 0; row < x; row++){
    this.cells[row] = []; // a row is just an array of CellInfo
    for(let col: number = 0; col < x; col++){
      // values are stored in the row array at the column position
      this.cells[row][col] = new CellInfo(row, col, [false, false, false]) 
    }
  }
}

After that you should be able to go trough them like this:

 div *ngFor="let cellrow of round.cells"

   div class = row; *ngFor="let cellcol of cellrow"

First for goes trough the rows, the 2nd for gets the cells.