将列表项移动到另一个列表Angular5

时间:2018-03-04 18:12:15

标签: javascript arrays angular javascript-objects angular5

您好我是Angular的新手,我试图在点击时将一个对象移动到另一个对象数组中。

这是我在Typescript文件中的一些代码

import { Component, OnInit } from "@angular/core";

@Component({
  selector: "app-roster-box",
  templateUrl: "./roster-box.component.html",
  styleUrls: ["./roster-box.component.css"]
})
export class RosterBoxComponent implements OnInit {
  itemCount: number = 4;
  btnText: string = "Move to Bench";
  goal;
  players: object = [
    {
      photo: "../../assets/images/lonzo.jpeg",
      name: "Lonzo Ball",
      position: "G",
      moves: 5

},

使用上面的代码我想点击一个按钮并将此播放器移动到替补席上。我也希望减少每个玩家剩余的动作量。下面是一些HTML。

<div class="starters">
  <div class=" col color-dark">
    <p>Starters</p>
  </div>

  <div class="player-block" *ngFor="let player of players">
    <div class="player-card">
      <img src="{{ player.photo }}" alt="">
      <p>{{ player.name }} {{ player.position }}</p>
      <p>Moves Remaining: {{moves}}</p>
    </div>
    <div>
      <form class="" action="">
        <input *ngIf="moves > 0" (click)="decreaseMoves()" class=" btn btn-sm waves-light" type="submit" value="{{ btnText }}">
      </form>

    </div>

  </div>
</div>

2 个答案:

答案 0 :(得分:0)

您好从阵列中删除一个项目,您可以使用拼接功能(https://www.w3schools.com/jsref/jsref_splice.asp

您的decreaseMoves函数应如下所示:

function decreaseMoves(playerIndex : number) { 
     moves = moves-1
     playerToMove = players.splice(playerIndex, 1);//splice return the removed item.
     bench.insert(playerToMove);
}

要将索引传递给函数,您需要添加一个绑定到* ngFor语句索引的变量,如下所示:

*ngFor="let player of players; let i = index"

然后用i作为参数调用decreaseMoves。

(click)="decreaseMoves(i)"

要使用其他组件,您应该声明服务。 该服务将设置玩家和工作台设置,你必须有一个像我上面提到的reduceMoves这样的功能为你做这个。

@Injectable()
class MyService {
      players : Players[] = []
      bench : Players[] = []
      moves : number = 0
      public function MovePlayerToBench(index) {
           moves -= 1
           playerToMove = this.players.splice(playerIndex, 1);//splice return the removed item.
           this.bench.insert(playerToMove);
      }
      public function GetPlayers() : Players[] { 
           return this.players
      }
      public function GetBench() : Players[] { 
           return this.bench
      }
      public function GetMoves() : number { 
           return this.moves
      }
}

答案 1 :(得分:0)

我的功能要求你将被点击的玩家添加到方法中,并在每个玩家身上拥有一些独特的属性,例如id。

<input *ngIf="moves > 0" (click)="decreaseMoves(player)" class=" btn btn-sm waves-light" type="submit" value="{{ btnText }}">

decreaseMoves(selectedPlayer: any): void {
    this.players = this.players.filter(player => {
        return player.id !== selectedPlayer.id;
    });
    const playerWithDecrementedMoves = Object.assign(selectedPlayer, {moves: selectedPlayer.moves - 1});
    this.bench.push(playerWithDecrementedMoves);
}

我使用纯js类示例制作了一个fiddle来测试逻辑。