创建绑定组件列表

Creating a list of bound components

我正在尝试制作一个显示一手牌的应用程序,并且这些牌可以在点击时更改。

我有一个手牌组件,一个卡牌组件。

hand.html:

<div class="col-lg-1" *ngFor="let card of cards">
        <app-card [card]="card"></app-card>
</div>

app-card 有自己的模板,可以显示牌的号码和花色。

hand.component.ts

import { Component, OnInit } from '@angular/core';
import { CardComponent } from '../card/card.component';

@Component({
  selector: 'app-hand',
  templateUrl: './hand.component.html'
})
export class HandComponent implements OnInit {
cards:CardComponent[] = [];

  constructor() {
    //Fill hand with 12 cards
    Array.from(Array(12)).forEach((x, i) => {
     this.cards.push( new CardComponent() );
    });

  }

  ngOnInit() {
  }

}

然后是 card.component.ts:

import { Component, OnInit, Input } from '@angular/core';

@Component({
  selector: 'app-card',
  templateUrl: './card.component.html'
})
export class CardComponent implements OnInit {

  constructor() {

  }

  @Input()
  card: Card;

  ngOnInit() {
    this.card.number = 2;
    this.card.suit = 'diamonds';
  }

  changeNumber( num ){
    this.card.number = num;
  }


}

interface Card{
    suit:string;
    number:number;
}

就目前而言,我得到了我的卡片列表,所有卡片都具有初始化的 2 钻石值。当我尝试触发 changeNumber 函数时,比如从 card 元素上的 onclick 事件,我收到一条错误消息“无法设置未定义的 属性 'number'。

所以我很困惑,为什么我可以在ngOnInit中设置初始值,但是再次尝试设置值,初始化后,卡片属性突然不存在(即使卡的值正在页面上显示)。

我仍在努力弄清楚@Input,可能会误用它。

你的卡片不应该是卡片组件的数组,而应该是卡片的数组。

所以不是这个:

cards:CardComponent[] = [];

应该是这样的:

cards: Card[] = [];

此代码:

<div class="col-lg-1" *ngFor="let card of cards">
        <app-card [card]="card"></app-card>
</div>

然后将为您创建适当数量的 CardComponent 实例。