iT邦幫忙

0

Angular 設計按鈕隨機取出陣列資料

請問若一個陣列包含多個objecthttps://ithelp.ithome.com.tw/upload/images/20211123/20143327ikopGWoTWG.png

例如這個

要怎麼設計出按按鈕能隨機取出裡面一組的value值
結果這樣https://ithelp.ithome.com.tw/upload/images/20211123/20143327Zk2owVYPTQ.png

希望是在html用插值綁定 顯示出來
在component 裡面應該要怎麼寫出隨機呼叫一組的功能讓html顯示
https://ithelp.ithome.com.tw/upload/images/20211123/20143327LkJXdrJqAR.png

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

2
albert41
iT邦新手 3 級 ‧ 2021-11-23 22:03:47
最佳解答

可以另外開一個 property 作為隨機選取的 Pokemon objet, 然後 template 綁定這個 property 做為顯示。

private _pokemonList: Pokemon[] = [ /* ... */ ];
public selectedPokemon: Pokemon;
public counter: number = 0;

ngOnInit() {
    getRandomPokemon();
}

public getRandomPokemon() {
    this.counter++;
    const randomIndex = Math.floor(Math.random() * this._pokemonList.length);
    this.selectedPokemon = this._pokemonList[randomIndex];
}

原來如此!謝謝你~

https://ithelp.ithome.com.tw/questions/10206309

我遇到一個延伸問題 如果object裡有屬性是any 上面的寫法會出錯誤訊息 any無法作為索引值 這個要怎麼辦

我要發表回答

立即登入回答