首页 > 解决方案 > Angular 不显示属性值

问题描述

我正在尝试对 ParentObject->Row->Cell 进行基本的 Angular 显示。所以 ParentObject 有一个 Rows 数组,每行有一个 Cells 数组。

我的父对象如下所示:

export class ParentObject implements OnInit {
  private gameRows: GamerowComponent[];

  constructor() {
    this.gameRows = [];

    for (var i: number = 0; i < 11; i++) {
      this.gameRows[i] = new GamerowComponent();
    }

  this.gameRows[1].gameCells[0].text = 'A';
  this.gameRows[2].gameCells[0].text = 'B';
  this.gameRows[3].gameCells[0].text = 'C';
  this.gameRows[4].gameCells[0].text = 'D';
  this.gameRows[5].gameCells[0].text = 'E';
  this.gameRows[6].gameCells[0].text = 'F';
  this.gameRows[7].gameCells[0].text = 'G';
  this.gameRows[8].gameCells[0].text = 'H';
  this.gameRows[9].gameCells[0].text = 'I';
  this.gameRows[10].gameCells[0].text = 'J';
}

GameRow 只是通过属性公开游戏单元:

export class GamerowComponent implements OnInit {
  private _gameCells: GamecellComponent[];

  constructor() {
    this._gameCells = [];
    for (var i:number=0; i < 11; i++) {
      this._gameCells[i] = new GamecellComponent();
    }
  }

  ngOnInit() {
  }

  get gameCells(): GamecellComponent[]{
    return this._gameCells;
  }

  set gameCells(value: GamecellComponent[]) {
    this._gameCells = value;
  }
}

而单元格只是一个文本和 cssclass 对象:

export class GamecellComponent implements OnInit {
  private _text: string;
  private _cssClass: string;

  constructor() {
    this._cssClass = 'tablemarker';
  }

  ngOnInit() {
  }

  get text(): string {
    return this._text;
  }

  set text(value: string) {
    this._text = value;
  }
  get cssClass(): string {
    return this._cssClass;
  }

  set cssClass(value: string) {
    this._cssClass = value;
  }
}

我为表格/行/单元格视图设置了 html:

父对象:

<table class="no-spacing">
  <tr *ngFor="let gameRow of gameRows">
    <app-gamerow></app-gamerow>
  </tr>
</table>

游戏行:

<app-gamecell *ngFor="let cell of gameCells"></app-gamecell>

游戏单元:

<td class="{{cssClass}}">{{text}}</td>

我正确地获得了一个包含 11 行和单元格的 HTML 表格。cssClass 已正确呈现,但文本从未显示。

当我在 11 行实例化后在浏览器中中断脚本时,它们的文本都设置正确。静态设置的 cssClass 文本如何工作(在类构造函数中设置)但从父级到子级的赋值却没有?

标签: angulartypescript

解决方案


你不应该直接实例化组件——把它留给 Angular。

相反,将数据保存在普通对象中,并将它们传递给组件。

GameCellComponent中,您可以添加一个输入,如下所示:

@Input()
public text: String;

@Input()
public cssClass: String;

然后,您可以传递这些值,如下所示:

<div *ngFor="let cell of gameCells">
  <app-gamecell [text]="cell.text" [cssClass]="cell.cssClass"></app-gamecell>
</div>

推荐阅读