我创建了一个玩家类表(全名,位置和排名),每个原始表都有一个c复选框。我如何实现这一点,当我点击复选框时,播放器的价值(原始版本)将出现在html中?
HTML代码:
<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代码(仅限相关行):
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);
}
}
}
答案 0 :(得分:0)
变化
value="player.fullName"
到
[value]="player.fullName"
哦,并将你的显示div更改为
<div *ngFor="let playerFullName of selectedBullsPlayers">{{playerFullName}}</div>
答案 1 :(得分:0)
使用ngModel
指令并将其绑定到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)
}
不要担心selected
ngModel
字段