Angular 2 根据数组放置组件

问题描述 投票:0回答:1

我是 Angular 2 的新手,我陷入了困境...... 我尝试为棋盘游戏创建一个棋盘(黑白棋,棋盘像国际象棋但单色) 我有一个类cellInfo(这里我想保存信息)

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

我有一个 CourtInfo 类(这里我创建了一个 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])
    }
  }
}

我有一个组件法院Comonent

  • 在.ts中我创建了一个courtInfo

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

(我命名为round是因为后来我想每轮刷新这个数组)

  • 在 html 中,我尝试从 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>

在 Court.component.css 中我有这个:

.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%;
}

CellComponent 本身的 shell 可以是一个 div,它的 shell(稍后)可以画一个圆,也可以不画一个圆。

但是自动取款机这不起作用,牢房没有添加到法院。 我不知道我是否必须在某个地方绑定,我猜这不是因为数组 [cells] 是一个类实习生......

我正在寻找一些提示

angular typescript
1个回答
0
投票

构建单元格信息的方式没有多大意义。您使行及其值都具有 CellInfo 类型,任何地方都没有数组。

应该更像这样:

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]) 
    }
  }
}

之后你应该能够像这样通过它们:

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

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

第一个 for 遍历行,第二个 for 获取单元格。

© www.soinside.com 2019 - 2024. All rights reserved.