So the problem I have is that I want to have a parameter being passed through two components in my Angular app, and when I change its value on the first component, the value also gets changed on the second one.
For the example here, I have a game component in which I can modify two numeral values (row and column), and a grid component (which is called in the game component) that would show an HTML table with the number of rows and columns from the game component which can be changed dynamically.
Here is 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>
Here is 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);
}
}
Here is grid.component.html
<table>
<tr *ngFor="let r of row">
<td *ngFor="let c of column">
test
</td>
</tr>
</table>
And 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 {
}
}