1. The Ghosting Symptom
The game state was technically valid; my internal board array correctly updated the values to represent the snake and fruit positions. However, the browser grid remained empty, ignoring the data state completely.
I initially suspected a change detection lifecycle issue or an asynchronous timing conflict. It seemed possible that the view was rendering before the initialization logic had finished processing the grid.
- Verified snake coordinates in the console.
- Checked board array values for 0, 1, and 2 identifiers.
- Confirmed that ngOnInit triggered the spawn function.
2. Unpacking the ngFor Interaction
The culprit lay in the HTML template. I had incorrectly assumed that the variable I was using in my `*ngFor` loop was the row index, when in reality, it was capturing the entire row object itself.
When attempting to render the cell, the logic was trying to treat the object reference as a primitive integer, which failed silently. This mismatch prevented the CSS classes from ever applying to the grid cells.
- Inspect the loop variable scope in the template.
- Verify if the variable references the index or the data object.
- Confirm that your CSS class binding matches the cell value type.
3. Data Integrity and Visualization
I needed to ensure that my board representation matched the grid structure. If the board is a 2D array, the nested loop must handle the row index and the column value independently.
By printing the specific cell value to the console during iteration, I confirmed that my template was attempting to read from an undefined index instead of the data property within the row.
- Use distinct variable names for row and cell.
- Print loop values to the template via interpolation for testing.
- Ensure the board initialization logic executes before the UI render.
4. Correcting the Loop Binding
The resolution was straightforward once I identified the variable naming error. I explicitly separated the row index from the row data in my loop declaration and adjusted the child loop to access the specific cell value.
After refactoring the template to reference the specific cell property, the snake and fruit nodes rendered immediately across the grid.
- Change `let row of board` to include index tracking.
- Reference the cell value specifically in the inner loop.
- Use Angular's trackBy function to optimize performance.
FAQ
Why did my console logs show data existed while the UI was empty?
This happens when the data model is correct, but your template's data binding is pointing to an incorrect property or object reference within the scope of your loop.
Is there a specific way to debug ngFor loops?
Yes, I recommend adding `{{ row | json }}` or specific cell values inside your HTML elements temporarily to see exactly what data the template is processing during runtime.