从* ngFor生成的输入标签中获取价值

时间:2019-11-23 14:25:22

标签: angular typescript input ngfor

我有一个使用* ngFor在表单上创建输入标签的组件。它基本上是看玩家的数组,并为每个玩家创建18个输入标签。最后,我有一个提交按钮。此按钮将启动一个方法,该方法应该遍历所有这些生成的输入标签,收集它们的值,并将它们添加到分数数组中。但是,当我尝试收集值时,出现错误提示值是null。如何查看并从输入标签中收集每个值?这有可能吗?这是代码:

HTML (ID的最后一个数字一直递增一个,直到id="id{{player.index}}-18"

...<mat-tab-group class="tabs">
        <mat-tab label="1">
          <div *ngFor="let player of playerAndID">
            <h3>{{ player.name }}</h3>
            <mat-form-field class="scoreInput">
              <input matInput placeholder="Score" id="id{{player.index}}-1">
            </mat-form-field>
          </div>
        </mat-tab>
        <mat-tab label="2">
          <div *ngFor="let player of playerAndID">
            <h3>{{ player.name }}</h3>
            <mat-form-field class="scoreInput">
              <input matInput placeholder="Score" id="id{{player.index}}-2">
            </mat-form-field>
          </div>
        </mat-tab>...

...<mat-tab label="18">
          <div *ngFor="let player of playerAndID">
            <h3>{{ player.name }}</h3>
            <mat-form-field class="scoreInput">
              <input matInput placeholder="Score" id="id{{player.index}}-18">
            </mat-form-field>
          </div>
          <div class="submit-game-button">    
              <button mat-raised-button (click)="addScoresToArray()" class="submit" type="button" routerLink="/results">Submit</button>
          </div>
        </mat-tab>

TS

addScoresToArray() {
    for (var i = 0; i < this.playerAndID.length; i++) {
      for (var j = 1; j < 19; j++) {
        var score = (<HTMLInputElement>document.getElementById("id{{i}}-{{j}}")).value;
        this.data.addToScores(parseInt(score), i);
      }
    }
  }

1 个答案:

答案 0 :(得分:1)

https://angular.io/api/forms/FormArray

您可以在formGroups中使用表单数组。