Search code examples
angulartypescriptinputngfor

Getting value from input tags generated by *ngFor


I have a component that uses *ngFor to create input tags on a form. It basically looks at an array of players and creates 18 input tags for each player. In the end, I have a submit button. This button starts a method that is supposed to go through each of these generated input tags, collect their values, and add them to an array of scores. However, when I try and collect the values, I get an error saying that the values are null. How can I go through and collect each value from the input tags? Is this even possible? Here is the code:

HTML (the last number of the ids increment by one all the way up to 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);
      }
    }
  }

Solution

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

    You can use form arrays in formGroups..