0

Ci-dessous est mon code pour une table html, je dois ajouter une fonction qui sur le clique sur le bouton déplace les lignes vers le haut ou vers le bas?Comment déplacer les lignes de haut en bas dans un tableau sur un clic de bouton dans Angular2?

<table class="table table-striped"> 
      <thead class="thead"> 
       <tr> 
        <th>Name</th> 
        <th>Key</th> 
        <th>Token</th> 
        <th>Color</th> 
        <th></th> 
       </tr> 
      </thead> 
      <tbody> 
       <tr *ngFor="let value of values"> 
        <td> 
         {{value.name}} 
        </td> 
        <td> 
         {{value.key}} 
        </td> 
        <td> 
         {{value.token}} 
        </td> 
        <td> 
         {{value.color}} 
        </td> 
        <td> 
         <button class="btn btn-success" (click)="editvalue(value);">edit</button> | 

        </td> 
       </tr> 
      </tbody> 
     </table> 

Pouvez-vous m'aider comment je peux faire cela? Merci pour l'aide.

+0

Bienvenue sur StackOverflow! Veuillez consulter les [guides pour poser des questions] (https://stackoverflow.com/help/asking), en particulier [comment créer un exemple minimal, complet et vérifiable] (https://stackoverflow.com/help/mcve) – AesSedai101

Répondre

0

Cela peut facilement se faire avec la mise à jour des index d'éléments de données comme suit.

Html

<table class="table table-striped"> 
      <thead class="thead"> 
       <tr> 
        <th>Name</th> 
        <th>Key</th> 
        <th>Token</th> 
        <th>Color</th> 
        <th></th> 
       </tr> 
      </thead> 
      <tbody> 
       <tr *ngFor="let value of values; let index = index;"> 
        <td> 
         {{value.name}} 
        </td> 
        <td> 
         {{value.key}} 
        </td> 
        <td> 
         {{value.token}} 
        </td> 
        <td> 
         {{value.color}} 
        </td> 
        <td> 
         <button class="btn btn-success" (click)="moveUp(value, index);">Move Up</button> 
        </td> 

        <td> 
         <button class="btn btn-success" (click)="moveDown(value, index);">Move Down</button> 
        </td> 
       </tr> 
      </tbody> 
     </table> 

Component.ts

moveUp(value, index) { 
    if (index > 0) { 
     const tmp = this.values[index - 1]; 
     this.values[index - 1] = this.values[index]; 
     this.values[index] = tmp; 
    } 
    } 

moveDown(value, index) { 
     if (index < this.values.length) { 
      const tmp = this.values[index + 1]; 
      this.values[index + 1] = this.values[index]; 
      this.values[index] = tmp; 
     } 
     }