mardi 30 octobre 2018

randomize array order Angular 4

im trying to randomize the order of my array in my Angular6 project. I have no idea how to do it and ended up tying to sort the aray with the Math.random function... (didn't work XD)

this is my code so far:

HTML

    <div style="background: darkcyan; width: 600px; height: 600px; margin: auto">
  <table>
    <tr *ngFor="let card of cards">
      <div id="" [ngStyle]="{'background-color': card.color}" style=" width: 100px; height: 125px; margin: 5px"></div>
    </tr>
  </table>
</div>
<button (click)="shuffle()">Shuffle Cards</button>

TypeScript

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

@Component({
  selector: 'app-memory-game',
  templateUrl: './memory-game.component.html',
  styleUrls: ['./memory-game.component.css']
})
export class MemoryGameComponent implements OnInit {
  cards = [];
  constructor() { }

  ngOnInit() {
    this.cards = [
        {
          'id': 1,
          'color': 'red'
        },
        {
            'id': 2,
            'color': 'green'
        },
        {
            'id': 3,
            'color': 'blue'
        },
        {
            'id': 4,
            'color': 'yellow'
        }
    ];
      this.shuffle();
  }

  public shuffle() {
      this.cards.sort(Math.random);
  }
}

I don't know if there is an easy solution, but I really hope someone is able to help me out..

Thanks




Aucun commentaire:

Enregistrer un commentaire