2017-05-07 38 views
0

家長子組件調用在父組件的方法,並返回一個值

HTML

<tr 
    [onTotalWeights]="totalWeights" 
    > 

代碼

totalWeights(): number { 
    return // Get sum of fields over the whole array 
    } 

兒童

@Input() onTotalWeights:() => number; 

    canApplyChanges() { 
    return this.onTotalWeights() <= 100 && this.form.valid; 
    } 

我想調用一個父子方法並返回一個值。

現在的問題是,當它被稱爲「this」關鍵字時,this.onTotalWeights()引用子組件內部的方法/變量,而不是來自父組件。不知何故,當我傳遞totalWeights函數時,上下文會丟失。

我該如何解決這個問題?

回答

0

這是正常的JS行爲。你可以通過調用.bind()

totalWeights(): number { ... } 

totalWeightsFn = this.totalWeights.bind(this); 
[onTotalWeights]="totalWeightsFn" 
+0

我也想過使用綁定的定製,但我已閱讀本:http://stackoverflow.com/questions/38102948/how-to-return-a-這個解決方案提到了丟失的上下文,但是沒有提供對上下文問題的綁定解決方案,或者我沒有看到它...... – Pascal

+0

它使用箭頭函數。使用箭頭函數'()=> {}'是完成相同操作的另一種方法。對於傳遞閉包,箭頭函數通常更方便,因爲傳遞函數引用'.bind()'通常更方便,因爲它不需要重複像someObject.someCallback((x)=> this.foo x))而不是'someObject.someCallbacl(this.foo.bind(this))''。 –

相關問題