2017-09-02 81 views
0

我會嘗試通過一個示例來解釋我的問題。Angular 2中的組件內部變量

如果我有這樣的事情在我的新組件:

... implements OnInit { 
    constructor(...) { } 
    variable = ""; 
    ngOnInit(): void { 
     ... 
    } 

那麼我可以用我的variable的ngOnInit內有this.,就像這樣:

this.variable = '1'; 

但我怎麼能使用我的變量內的一個子函數的ngOnInit?例如:

ngOnInit(): void { 
     ... 
     // here I want to use another function with my `variable` 
     // something like: 
     // myFunc() { 
     // this.variable = '2'; 
     // } 
     ... 
    } 

謝謝。

回答

0

只是使用箭頭功能,你很好,因爲它會自動綁定到this

ngOnInit(): void { 

    let somefunc: any =() => { 
     this.variable = "got here"; 
    }; 
} 

希望幫助