簡體   English   中英

將列表項移動到另一個列表Angular5

[英]Move a list item into another list 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>

嗨,要從數組中刪除某項,您可以使用splice函數( https://www.w3schools.com/jsref/jsref_splice.asp

您的reductionMoves函數應如下所示:

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作為參數調用reduceMoves。

(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
      }
}

我的功能要求您將要單擊的播放器添加到方法中,並在每個播放器上具有一些唯一的屬性,例如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類例如來測試邏輯。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM