angular - 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 文本如何工作(在类构造函数中设置)但从父级到子级的赋值却没有?
解决方案
你不应该直接实例化组件——把它留给 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>
推荐阅读
- spring-mvc - 如何通过 GraphQL 中的复合对象进行查询?
- jquery - 表中没有可用数据 - 数据表 jquery 问题
- docker - nftable fib 规则与节点目标 ip 的数据包不匹配
- ios - 当使用 xctestrun 运行自动化时,通过 fastlane run_tests 打印出大量不需要的日志“设备不支持无线同步”。
- python - 从 MXNet 1.7.0/Gluon 中的预训练 BERT 网络中提取词嵌入符号块
- encryption - 使用 Hashicorp Vault Transit Engine 加密字符串列表
- quarkus - 调试使用 quarkus-container-image-jib 打包的 Quarkus 应用程序
- r - write_xlsx(all_trips, "trips.xlsx") 错误:libxlsxwriter 中的错误:“工作表行或列索引超出范围。”
- javascript - 无法在 Safari 上使用 Tab 键导航来聚焦按钮
- python - 按两列分组并比较一列的行