當我試圖做到這一點:如何在Angular2表達式中檢查isNaN?
dividerColor="{{isNaN(+price) ? 'warn' : 'primary'}}"
它給我這個錯誤:
browser_adapter.ts:82 ORIGINAL EXCEPTION: TypeError: self.context.isNaN is not a function
我如何確認我的對象是在Angular2表達不多少?
當我試圖做到這一點:如何在Angular2表達式中檢查isNaN?
dividerColor="{{isNaN(+price) ? 'warn' : 'primary'}}"
它給我這個錯誤:
browser_adapter.ts:82 ORIGINAL EXCEPTION: TypeError: self.context.isNaN is not a function
我如何確認我的對象是在Angular2表達不多少?
發生這種情況是因爲表達式是針對視圖上下文計算的,而不是eval
,在模板中不提供JS全局變量。
考慮Number.isNaN
被polyfilled,在技術上可以與
{{ (+price).constructor.isNaN(+price) ... }}
做雖然可以認爲是黑客攻擊。我會建議將每個幫助器函數公開爲類屬性或管道。
而不是暴露組件中的isNan函數,並在模板中應用一些規則,我認爲這是暴露一個具有商業意義的屬性更好的選擇。 例如:
class MyComp {
hasPrice: boolean;
someAction() {
...
this.hasPrice = !isNaN(this.item.price);
}
}
<div dividerColor="{{hasPrice ? 'warn' : 'primary'}}"></div>
您可以將該功能作爲類的屬性:
class MyComponent {
isNaN: Function = Number.isNaN;
}
<div>dividerColor="{{isNaN(+price) ? 'warn' : 'primary'}}"</div>
當我嘗試,dividerColor =「{{(+價格).constructor.isNaN(+價格) ?'warn':'primary'}}「,它給了我這個錯誤:browser_adapter.ts:82 ORIGINAL EXCEPTION:TypeError:self._NgModel_74_7.constructor.isNaN不是函數。你喜歡plunkr還是其他我可以測試的東西? – Vicheanak
我認爲最好只是添加一個方法到你的組件'isNan(val){return isNan(val); }'並像你在你的問題中一樣使用它。 –
@Vicheanak答案明確指出Number.isNaN [需要多邊填充,它是ES6特性](https://github.com/zloirock/core-js/blob/master/library/fn/number/is-nan .js文件)。沒有polyfill就無法工作。它與一個polyfill工作。正如已經說過的,更簡單的方法是將isNaN heper函數暴露爲類方法。 – estus