Angular:如何重置子组件 [英] Angular: How to reset child components

查看:560
本文介绍了Angular:如何重置子组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经编写了一个Java后端,用作我的服务器并将提供所有数据. 前端是Angular 8应用程序.

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

我已经在stackblitz中创建了前端应用程序的剥离版本: https://stackblitz.com/edit/angular-code-game

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

游戏包含1个父组件(GAME)和4个(相同)子组件(COUNTER). 当我开始一个新的(游戏实例)游戏时,我希望将计数器设置为其初始状态.

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.

我已经做过一些研究,我认为我应该使用@ViewChild,但是我不知道如何在我的父组件文件中重置我的4个子组件.

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.

为了说明我的问题:

  • 取消选择所有计数器上的数字,直到剩下1个为止.
  • 代码将被填充在底部(蓝色金库框)
  • 单击开始新游戏"按钮->按钮应重置为初始状态(绿色)

app.component.ts内部应该有一些逻辑:

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

知道如何解决此问题的人吗?

Anyone who knows how to fix this?

推荐答案

由于您有多个,所以您可能希望ViewChildren ......假设您的子组件上有一些reset()方法,这些方法会将其置于初始状态,执行此操作:

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:

在父母中:

@ViewChildren(CounterComponent)
childGames: QueryList<CounterComponent>

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

根据需要致电resetAll().

这是示例闪电战: https://stackblitz.com/edit/angular-code-game-aq7y5g?file=src/app/app.component.ts

这篇关于Angular:如何重置子组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆