2016-11-16 53 views
7

有沒有在angular2綁定中使用數學函數的方法?angular2綁定中的數學函數

例如

<div class="partition-panel"> 
       <b class="pull-left">{{Math.round(variable/12*2)}}</b> 
       <b class="pull-right">{{Math.round(variable/12*2)}}</b> 
</div> 

時嘗試使用此我得到錯誤

Cannot read property 'round' of undefined 

而且類似的問題的答案爲angular1

+1

問題是,從模板中你只能訪問你的'Component'的局部範圍,所以你必須定義一個輔助方法或將'window.Math'賦值給Adrien建議的成員變量。 – rinukkusu

回答

26

你可以試試這個:

@Component({ 
    selector: 'my-app', 
    template: ` 
    <div> 
     <h2>Hello {{this.Math.round(this.number)}}</h2> 
    </div> 
    `, 
}) 
export class App { 
    number: number; 
    Math: any; 
    constructor() { 
    this.Math = Math; 
    this.number = 2.5 
    } 
} 
+0

這工作,但我不得不將聲明移動到模板需要Math的組件。 – RSinohara

+0

你應該也可以避免在構造函數初始化數學,並簡單地寫: Math:Math = Math; – 39ro