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 *ngFor="let nft of nfts">
<img src="{{nft.image}}" >
<div >
<h4 >{{nft.name}}</h4>
<a routerLink="/">NFT collection</a>
<p>Price: <span>300</span></p>
<button ><i ></i></button>
<a routerLink="/nft-details/:id" ></a>
</div>
</div>
I hope someone can help me! Thank you!
CodePudding user response:
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 >
<img src="{{nfts[randomIndex].image}}" >
<div >
<h4 >{{nfts[randomIndex].name}}</h4>
<a routerLink="/">NFT collection</a>
<p>Price: <span>300</span></p>
<button ><i ></i></button>
<a routerLink="/nft-details/:id" ></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)
})
}
}
CodePudding user response:
Use Object.map
and iterate the elements that use the same syntax.