0

I created a table of players class (fullname, position and ranking), the table has c checkbox for each raw. How can I implement so when I click on the checkbox, the value of the player (for that raw) will appear in the html?

the HTML code:

<table>
  <tbody>
    <tr *ngFor="let player of bullsPlayers; let i = index;">
      <td>{{player.fullName}}</td>
      <td>{{player.position}}</td>
      <td>{{player.ranking}}</td>
      <td>
        <input 
          type="checkbox" 
          class="form-check-input" 
          [id]="bullsPlayers[i]" 
          [name]="bullsPlayers[i]"
          value="player.fullName" 
          (change)="addOrRemoveBullsPlayer($event.target.value)" />
      </td>
    </tr>
  </tbody>
</table>
    
<div>{{selectedBullsPlayers}} </div>

TS code (only related lines):

bullsPlayers = [];
selectedBullsPlayers = [];
    
constructor(private _playerService: PlayerService) {}
    
ngOnInit (){
  this._playerService.getPlayers()
    .then(players => this.players = players)
    .catch(error => console.log(error));
  this._playerService.getBullsPlayers()
    .then(players => this.bullsPlayers = players)
    .catch(error => console.log(error));
}
    
addOrRemoveBullsPlayer(value: string) {
  var indexOfEntry = this.selectedBullsPlayers.indexOf(value);
  if(indexOfEntry < 0) {
    this.selectedBullsPlayers.push(value);
  } else {
    this.selectedBullsPlayers.splice(indexOfEntry, 1);
  }
}
2
  • what you mean by the value of the player ? Commented Dec 2, 2017 at 10:49
  • for example - it's full name Commented Dec 2, 2017 at 12:21

2 Answers 2

1

use ngModel directive and bind it to player.selected

html:

<td>
  <input
    type="checkbox"
    class="form-check-input"
    [id]="bullsPlayers[i]"
    [name]="bullsPlayers[i]"
    [(ngModel)]="player.selected"
    value="player.fullName"
    (change)="updateBullsPlayer()"/>
</td> 

component.ts:

updateBullsPlayer() {
  this.selectedBullsPlayers = selectedBullsPlayers.filter((item) => item.selected)
}

don't worry about selected field it will added automatically by ngModel

Sign up to request clarification or add additional context in comments.

Comments

0

change

        value="player.fullName"

to

        [value]="player.fullName"

Oh, and change your display div into something like

        <div *ngFor="let playerFullName of selectedBullsPlayers">{{playerFullName}}</div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.