Search code examples
angulardetectiontic-tac-toe

Is there a way to detect state of multiple angular components?


I followed a tutorial to make a Tic-Tac-Toe app and am now trying to add further functionality on my own.

The draw condition is the main hurdle I am stuck at. Each tile in the tic tac toe grid is it's own Angular Component that has been created using *ngFor directive. Here's that code.

<app-square 
        *ngFor="let val of squares; let i = index" 
        [value]="val"
        (click)="makeMove(i)"> 

    </app-square>

Upon clicking, the button checks for a pre existing value and then if absent, applies a value (X or O) based on whose turn it is.

I have tried using click count based methods but none have panned out. Also, the winning condition is designed so that if a variable "winner" is no longer null, it would announce whatever is in winner variable. Here's the code for that.

<h2 *ngIf="winner">
    Player {{ winner }} won the game!
</h2>

Is there any way I can design a flag for each button that can be used to detect if all of them have values in them, thereby implying that the game has resulted in a draw?


Solution

  • You already have everything in place. Just, in the parent component, add an additional check for an array of squares. If it is filled with Ok values, set winner to true.

    It might look like this

    this.winner = this.squares.every(x=>x===true)
    

    Instead of true, use the value you are using.