skip to Main Content

I am creating a marketplace in angular and I have created the marketplace page which is populated by a remote json created with mockapi. The problem is that in the homepage I want to display a single item (possibly random) from the same json but with *ngFor it displays all the items.

This is my code:

export class DashboardComponent implements OnInit {

    nfts: any;
    constructor(
        private http: HttpClient,
    ) {

    }

    ngOnInit(): void {
        this.getNfts()
    }

    getNfts() {
        this.http.get('https://63bd1526fa38d30d85d88179.mockapi.io/NFT/v1/metadata').subscribe((data) => {
            this.nfts = data
        })
    }

}

// HTML

            <div class="card cards card-p" *ngFor="let nft of nfts">
                <img src="{{nft.image}}" class="card-img-top">
                <div class="card-body">
                    <h4 class="nft-title">{{nft.name}}</h4>
                    <a class="nft-collection mb-3" routerLink="/">NFT collection</a>
                    <p>Price: <span>300</span></p>
                    <button class="button heart text-end"><i class="fa-solid fa-heart"></i></button>
                    <a routerLink="/nft-details/:id" class="stretched-link"></a>
                </div>
            </div>

I hope someone can help me! Thank you!

2

Answers


  1. Use Object.map and iterate the elements that use the same syntax.

    Login or Signup to reply.
  2. If all you want to do is display a single element (random) from an array then you can use something like "Math.floor(Math.random() * this.nfts.length)" to get a random element from the array and display that array.

    so the html will look something like this

    <div class="card cards card-p">
      <img src="{{nfts[randomIndex].image}}" class="card-img-top">
      <div class="card-body">
        <h4 class="nft-title">{{nfts[randomIndex].name}}</h4>
        <a class="nft-collection mb-3" routerLink="/">NFT collection</a>
        <p>Price: <span>300</span></p>
        <button class="button heart text-end"><i class="fa-solid fa-heart"></i></button>
        <a routerLink="/nft-details/:id" class="stretched-link"></a>
      </div>
    </div>
    

    The Javascript

    export class DashboardComponent implements OnInit {
        nfts: any;
        randomIndex = 0;
        constructor(
            private http: HttpClient,
        ) {
    
        }
    
        ngOnInit(): void {
            this.getNfts()
        }
    
        getNfts() {
            this.http.get('https://63bd1526fa38d30d85d88179.mockapi.io/NFT/v1/metadata').subscribe((data) => {
                this.nfts = data
                this.randomIndex = Math.floor(Math.random() * this.nfts.length)
            })
        }
    
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search