0

enter image description here

I'm making an othello game board on a HTML page using Angular. The board is made of a 2d number array and I show this using <table> tag on a web page. The following is what I've done.

A HTML Page(app.component.html):

<table>
    <tr *ngFor="let line of board">
        <td *ngFor="let cell of line" (click)="click(cell)">
            <div class="black" *ngIf="cell == 1">●</div>
            <div class="white" *ngIf="cell == 2">●</div>
        </td>
    </tr>
</table>

The array initialized in JS(app.component.ts):

board =[
    [0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 1, 2, 0, 0, 0],
    [0, 0, 0, 2, 1, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0],
]

Empty cells have the value of 0, while black and white have 1 and 2 respectively. The next thing I have to do is to get the index of the clicked cell, check if it's empty or not.

If every cell has its own value to identify, I can easily figure out which cell is clicked using .indexOf, but all the empty cells have the same value of 0.

One idea I have is to declare an array of an object containing an id field or something like below:

export class Cell{
    status: number//0, 1 or 2
    id: number//0 ~ 63
}

Can I use some better idea beside this?

1 Answer 1

1

You can get each index of the rows and cells and pass them into the function click. This will passes the current index of the row and cell, which was clicked.

<tr *ngFor="let line of board; let lineIndex = index">
    <td *ngFor="let cell of line; let cellIndex = index" 
        (click)="click(cell, lineIndex, cellIndex)">
        <div class="black" *ngIf="cell == 1">●</div>
        <div class="white" *ngIf="cell == 2">●</div>
    </td>
</tr>
Sign up to request clarification or add additional context in comments.

2 Comments

you are awesome. btw, is that index automatically created when i call *ngFor? i ran this code and all those indices properly get values starting with 0.
Yes, they automatically created when you use *ngFor

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.