angular - 如何通过Angular上的组件传递动态参数?
问题描述
所以我遇到的问题是我想让一个参数通过我的 Angular 应用程序中的两个组件传递,当我在第一个组件上更改它的值时,第二个组件的值也会改变。
对于此处的示例,我有一个游戏组件,我可以在其中修改两个数值(行和列),以及一个网格组件(在游戏组件中调用),它将显示一个带有行数和列数的 HTML 表格来自可以动态更改的游戏组件。
这是game.component.html
<header>
<h1>
Test App
</h1>
</header>
<div>
Number of rows: {{row}}
<button (click)="addRow()" >+</button>
<button (click)="removeRow()" >-</button>
</div>
<div>
Number of columns: {{column}}
<button (click)="addColumn()" >+</button>
<button (click)="removeColumn()" >-</button>
</div>
<grid [row]="row" [column]="column" >
</grid>
这是game.component.ts
import { Component, OnInit, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'game',
templateUrl: './game.component.html',
styleUrls: ['./game.component.css']
})
export class GameComponent implements OnInit {
@Output() rowChange = new EventEmitter<number>();
@Output() columnChange = new EventEmitter<number>();
constructor() { }
ngOnInit(): void {
}
row = 5;
column = 5;
addRow(){
this.changeRow(1);
}
removeRow(){
this.changeRow(-1);
}
changeRow(delta: number){
this.row = Math.max(0, this.row + delta);
this.rowChange.emit(this.row);
}
addColumn(){
this.changeColumn(1);
}
removeColumn(){
this.changeColumn(-1);
}
changeColumn(delta: number){
this.column = Math.max(0, this.column + delta);
this.columnChange.emit(this.column);
}
}
这是grid.component.html
<table>
<tr *ngFor="let r of row">
<td *ngFor="let c of column">
test
</td>
</tr>
</table>
和grid.component.ts
import { Component, OnInit, Input } from '@angular/core';
@Component({
selector: 'grid',
templateUrl: './grid.component.html',
styleUrls: ['./grid.component.css']
})
export class GridComponent implements OnInit {
@Input() row: number;
@Input() column: number;
constructor() { }
ngOnInit(): void {
}
}
解决方案
推荐阅读
- java - 为什么 compareTo BigInteger while 循环不退出?
- html - 当我用关键帧制作另一个动画时,为什么不能为 scali 设置动画?
- sql - 结合使用 case 子句 SQL Server 2014 从别名列中删除 Char 10、Char 13 字符
- javascript - 缺少数字算法超时错误 (JavaScript)
- javascript - Bootstrap vue popover中带有v-show的动态内容
- angular - Angular 和 VS Code 禁用自动重新加载/刷新
- angular - ChartJs - 是否可以在一个数据集中仅显示工具提示?
- laravel - Laravel 获取属于列的数据
- python - Python:使用类似 zip 的函数同时迭代可迭代和 saclar
- java - 同步骆驼路线的等待时间