【问题标题】:Selecting a rendered component in Angular在 Angular 中选择渲染组件
【发布时间】:2020-11-28 21:04:21
【问题描述】:

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

我有一个组件 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 组件上的“flipped”属性不会被切换。

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

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

【问题讨论】:

    标签: angular


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-21
      • 1970-01-01
      • 1970-01-01
      • 2018-08-23
      • 2018-08-24
      • 2017-12-04
      • 1970-01-01
      • 2020-11-08
      相关资源
      最近更新 更多