簡體   English   中英

如何在 Angular 中使用帶有輸入數組的訂閱以及如何對它們的值求和?

[英]How to use subscribe in Angular with an array of inputs and how to sum their values?

我有一個反應式 angular 表格。 該表格是一個簡單的記分牌。 我希望能夠將回合加在一起以構成分數。 因此,當一輪結束並輸入該輪的分數時,它會將所有總輪數加總到該玩家的分數中。

這是我到目前為止所擁有的:

表單.組件.html

<section [formGroup]="board">
  <table class="table table-bordered" formArrayName="scoreboard">
    <tr>
      <th colspan="2">Scoreboard:</th>
      <th width="150px">
        <button type="button" (click)="addPlayer()" class="btn btn-primary">
          Add Additional Players
        </button>
      </th>
    </tr>
    <tr
      *ngFor="let quantity of scoreboard().controls; let i = index"
      [formGroupName]="i"
    >
      <td>
        Name :
        <input type="text" formControlName="name" class="form-control" />
      </td>
      <td>
            Round1
            <input type="text" formControlName="round1" />
            Round2
            <input type="text" formControlName="round2" />
      </td>
      <td>
        Score:
        <input type="text" formControlName="score" class="form-control" />
      </td>
    </tr>
  </table>

  {{ this.board.value | json }}
</section>

表單.component.ts

import { Component } from '@angular/core';
import { FormBuilder, FormGroup, FormArray } from '@angular/forms';

@Component({
  selector: 'app-basic-form',
  templateUrl: './basic-form.component.html',
  styleUrls: ['./basic-form.component.css']
})
export class BasicFormComponent  {
  board: any;

  constructor (private fb: FormBuilder) {
    this.board = this.fb.group({
      scoreboard: this.fb.array([this.game(), this.game()])
    });
  }
  scoreboard() : FormArray {  
    return this.board.get("scoreboard") as FormArray  
  }  

  game(): FormGroup {  
    return this.fb.group({  
      name: '',  
      score: '',
      round1: [''],
      round2: ['']
    })  
  }       
  addPlayer() {  
    this.scoreboard().push(this.game());  
  }  
  onSubmitForm () {
    console.log(this.board.value);
  }
}

真的剛剛開始學習 Angular 並想自己嘗試一些東西。 如果您可以提供詳細信息或向我展示某個地方,我可以了解有關該解決方案的更多信息,那就太好了!

您可以聆聽您組的控制值變化,並相應地更新分數。 您的表單數組由表單組列表(游戲函數的返回值)組成,這些組具有保存各自索引值的控件,因此當您創建表單組時,您可以收聽 round1 和 round2 變化,並且相應地更新分數。 例如,我在下面所做的是使用combineLatest function 合並兩個值變化可觀察值(round1 + round2),然后相應地更新分數。 所以現在推送到您的表單數組的每個新表單組都將有自己的值更改偵聽器並將更新分數。

  game(): FormGroup {  
    const gameGroup = this.fb.group({  
      name: '',  
      score: '',
      round1: [''],
      round2: ['']
    });
    combineLatest(gameGroup.get('round1').valueChanges,gameGroup.get('round2').valueChanges)
    .subscribe(([r1,r2]) => gameGroup.get('score').setValue(Number(r1) + Number(r2)));
    return gameGroup;
  }       

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM