Reputation: 13
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);
}
}
Upvotes: 0
Views: 13386
Reputation: 37403
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
Upvotes: 1
Reputation: 199
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>
Upvotes: 0