2 回答

TA貢獻(xiàn)1821條經(jīng)驗(yàn) 獲得超6個(gè)贊
了解模板代碼的作用很重要:它迭代并elements.Event.Texts調(diào)用textSelector每個(gè)元素。只要返回 true,就會(huì)創(chuàng)建一個(gè)元素。textSelectorp
我會(huì)建議一種不同的方法。只調(diào)用一次函數(shù),因?yàn)槟恍枰粋€(gè)值。
<p *ngIf="textSelector(elements.Event.Texts)">{{bestText}}</p>
這就是我編寫函數(shù)的方式。我會(huì)使用一個(gè)數(shù)組來設(shè)置優(yōu)先級,所以它更易于維護(hù)。
const order = ["VeryShort", "Short", "Medium"];
textSelector(items: any[]) {
let bestItem;
for (const item of items) {
if (item.Type === order[0]) {
this.bestText = item.Value;
return true;
}
if (!bestItem) {
bestItem = item;
} else if (order.indexOf(item.Type) < order.indexOf(bestItem.Type)) {
bestItem = item;
}
}
if (!bestItem) {
return false;
}
this.bestText = bestItem.Value;
return true;
}
如果您有任何問題或需要解釋,請告訴我。

TA貢獻(xiàn)1845條經(jīng)驗(yàn) 獲得超8個(gè)贊
試試這個(gè)。它可能有效
textSelector(item: any) {
if (item.Type === 'VeryShort') {
this.bestText = item.Value;
return true;
} else if (item.Type === 'Short') {
this.bestText = item.Value;
return true;
} else if (item.Type === 'Medium') {
this.bestText = item.Value;
return true;
} else {
return false;
}
}
添加回答
舉報(bào)