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
Use
Object.map
and iterate the elements that use the same syntax.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
The Javascript