我有一个json对象,其中包含一个代表一个棋盘的坐标列表和另一对代表另一个坐标的坐标(在我的例子中是一个乌龟)。
我可以让董事会好起来,但我无法弄清楚如何渲染乌龟。
我是否需要使用以下内容:
ang_element = angular.element(id=turtlePos.X + "," + turtlePos.Y ); // Get element by id and color background
还是有更多" Angular"方式是什么?
这是表格(位置0,1应该有css类" turtle"):
游戏模型component.html:
<table *ngIf="gameModel">
<tr *ngFor="let row of gameModel.board.boardTiles; let i = index">
<td [attr.id]="i + ',' + y" [ngClass]="{'mine': column == 1, 'exit': column == 2}" *ngFor="let column of row; let y = index">({{i}},{{y}})</td>
</tr>
</table
游戏模型component.ts:
import { Component, OnInit } from '@angular/core';
import { GameModel } from '../game-model';
import { GameService } from '../game.service';
@Component({
selector: 'app-game-model',
templateUrl: './game-model.component.html',
styleUrls: ['./game-model.component.css']
})
export class GameModelComponent implements OnInit {
gameModel: GameModel;
constructor(private gameService: GameService) { }
loadedGameModel(gameModel: Object) {
console.log('Loaded GM');
console.log(JSON.stringify(gameModel));
this.gameModel = GameModel.fromJsonObj(gameModel['Result']);
}
ngOnInit() {
console.log('Getting game data');
this.getGame();
}
getGame(): void {
this.gameService.getGame()
.subscribe(gameModel => this.loadedGameModel(gameModel));
}
}
游戏model.component.css:
table, th , td {
border: 1px solid grey;
border-collapse: collapse;
padding: 50px;
}
table tr:nth-child(odd) {
background-color: #f1f1f1;
}
table tr:nth-child(even) {
background-color: #ffffff;
}
.mine {
background-color: red;
}
.exit {
background-color: blue;
}
来自这个json:
{
"Turtle": {
"CurrentPosition": {
"Direction": 0,
"X": 0,
"Y": 1
}
},
"Board": {
"BoardTiles": [
[
{
"TileAssignment": 0
},
{
"TileAssignment": 0
},
{
"TileAssignment": 0
},
{
"TileAssignment": 0
}
],
[
{
"TileAssignment": 0
},
{
"TileAssignment": 1
},
{
"TileAssignment": 0
},
{
"TileAssignment": 0
}
],
[
{
"TileAssignment": 0
},
{
"TileAssignment": 0
},
{
"TileAssignment": 0
},
{
"TileAssignment": 0
}
],
[
{
"TileAssignment": 0
},
{
"TileAssignment": 1
},
{
"TileAssignment": 0
},
{
"TileAssignment": 1
}
],
[
{
"TileAssignment": 0
},
{
"TileAssignment": 0
},
{
"TileAssignment": 2
},
{
"TileAssignment": 0
}
]
],
"Width": 5,
"Height": 4
}
}
答案 0 :(得分:1)
angular中的每个组件都有生命周期钩子事件。您可以在ngAfterViewInit事件中访问DOM。见https://angular.io/api/core/AfterViewInit
所有活动的参考:https://angular.io/guide/lifecycle-hooks
ngAfterViewInit() {
ng_element = angular.element(id=turtlePos.X + "," + turtlePos.Y );
//other code
}
答案 1 :(得分:1)
我假设你有一个乌龟的坐标,你需要根据表格的坐标将它放在你的桌面网格上。另外,我假设你有一个名为 turtle 的组件。
我会尝试在你的双ngFor
次迭代中绘制它:
<table *ngIf="gameModel">
<tr *ngFor="let row of gameModel.board.boardTiles; let i = index">
<td [attr.id]="i + ',' + y"
[ngClass]="{'mine': column == 1, 'exit': column == 2}"
*ngFor="let column of row; let y = index">
({{i}},{{y}})
<turtle *ngIf="turtlePos.X === i && urtlePos.Y === y"></turtle>
</td>
</tr>
</table>
turtle
组件将仅在指定的坐标上呈现