Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular: How to reset child components

Tags:

angular

I have written a Java backend that is used as my server and will serve all data. The frontend is an Angular 8 application.

I've created a stripped version of my frontend application in stackblitz: https://stackblitz.com/edit/angular-code-game

The game consists of 1 parent component (GAME) and 4 (the same) child components (COUNTER). When I start a new (instance of the) game, I want the counters to be set to their initial state.

I have done some research, and I think I should use @ViewChild, but I don't know how I can get to reset my 4 child components in my parent component file.

To illustrate my problem:

  • Deselect the numbers on all counters until 1 of each is left.
  • The code will be filled at the bottom (blue vault box)
  • When you click on the button "start new game" -> the buttons should be reset to their initial state (green)

There should be some logic inside the app.component.ts:

Anyone who knows how to fix this?

like image 834
Kevin Rovers Avatar asked Feb 13 '26 16:02

Kevin Rovers


1 Answers

since you have multiple, you probably want ViewChildren... suppose your child components have some reset() method on them that puts them to their initial state, do this:

in parent:

@ViewChildren(CounterComponent)
childGames: QueryList<CounterComponent>

resetAll() {
  this.childGames.forEach(c => c.reset()); // or whatever you want to do to it here
}

call resetAll() as needed.

here is a sample blitz: https://stackblitz.com/edit/angular-code-game-aq7y5g?file=src/app/app.component.ts

like image 200
bryan60 Avatar answered Feb 16 '26 08:02

bryan60