首页 > 解决方案 > 如何通过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 {
  }

}

标签: angularcomponents

解决方案


推荐阅读