首页 > 解决方案 > 在 Angular 中选择渲染组件

问题描述

我正在尝试构建一个翻牌游戏。你需要点击两张卡片,它们会翻转。如果他们是一对,他们保持翻转,如果不是,他们翻转回来。

我有一个组件 Card,它在单击时调用一个 FlipCard 函数,以及一个跟踪整体游戏统计数据的 GameService。

flipCard() {

if (this.gameService.flippedCards  < 2)
{
  this.flipped = true;
  this.gameService.flippedCards++;
  this.gameService.flippedCardsIds.push(this.cardNumber);

  if (this.gameService.flippedCards  == 2)
    if (this.gameService.flippedCardsIds[0][0] == this.gameService.flippedCardsIds[1][0])
    {
      // Flip back the cards
      // this.gameService.flippedCardsIds remembers the currently flipped card Ids
      this.gameService.flippedCards = 0;
    }
}

这是 GameService 结构:

cards = Array<number>();

flippedCards: number = 0;
flippedCardsIds = Array<string>();
index: number=0;

constructor() { }

generateRandomCards() {
  let newCard;
  newCard = Math.floor(Math.random() * Math.floor(16));
  if (this.cards.length < 16)
  {
    if (!this.cards.includes(newCard))
      this.cards.push(newCard);
  
    this.generateRandomCards();
  }

}

我的问题是,如果它们不是一对,我如何跟踪并重新翻转我之前点击的卡片?使用 ID 将不起作用,因为 Card 组件上的“翻转”属性不会被切换。

对于当前的卡片,我可以这样做。flipCard()。

欢迎任何帮助,我希望我的解释足够清楚

标签: angular

解决方案


通过在向父组件发出“flipCard”事件时传递“this”,然后将其存储到数组中来解决它。


推荐阅读