To learn the basics of Angular, I decided to write a little sudoku. Here's the html for the dynamically constructed Sudoku grid:
<div
*ngIf="(this.sudokuGenerated && !this.sudokuSolved) || this.isEmptySudoku">
<table id="grid" style="border-collapse: collapse;">
<tr class="grid-row" *ngFor="let row of this.displaySudoku.workingCopy; index as i;">
<td #sudokucell class="grid-cell" *ngFor="let cell of row; index as j;" (click)="this.setNumberInCell(i, j, $event)">
<span class="empty-cell" *ngIf="this.displaySudoku.workingCopy[i][j] == 0"> </span>
<span class="empty-cell" *ngIf="this.displaySudoku.workingCopy[i][j] != 0 && this.displaySudoku.grid[i][j] == 0">{{cell}}</span>
<span class="given-cell" *ngIf="this.displaySudoku.workingCopy[i][j] != 0 && this.displaySudoku.grid[i][j] != 0">{{cell}}</span>
</td>
</tr>
</table>
As you can see, there is a click event on every td. The following method is called on click. In the method, the previous selected number is recorded in the selected cell (td). After entering the number, the number is checked for sudoku solution. If this is wrong, cell (td) gets a css class of "wrong cells" that changes the background color to red:
setNumberInCell(row: number, col: number, event: Event): void {
if (this.selectedNumber != null && !this.sudokuSolved && this.displaySudoku.grid[row][col] == 0) {
this.displaySudoku.workingCopy[row][col] = this.selectedNumber;
this.checkAndRenderErrorCell(row, col, this.selectedNumber, event.srcElement);
}
}
checkAndRenderErrorCell(row: number, col: number, nr: number, element: Element): void {
if (this.checkMode && element != undefined) {
if (this.displaySudoku.workingCopy[row][col] != this.displaySudoku.solution[row][col]) {
console.log(element);
this.renderer.addClass(element, 'error-cell');
this.renderer.removeClass(element, 'selected-cell');
}
}
}
, , , srcElement , .
: 0 ( 0 0), td- 0 1. , , td- .
, , .
!
* * event.target event.currenTarget.