簡體   English   中英

Angular 2中組件內部的變量

[英]Variable inside of a component in Angular 2

我將嘗試通過一個例子來解釋我的問題。

如果我在新組件中有類似的內容:

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

然后,我可以在ngOnInit中使用我的variable this. ,就像這樣:

this.variable = '1';

但是,如何在ngOnInit的子函數中使用我的變量? 例如:

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

謝謝。

只需使用箭頭函數,你會很好,因為它會自動綁定到this

ngOnInit(): void {

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

希望能有所幫助

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM