简体   繁体   中英

Variable inside of a component in Angular 2

I'll try to explain my question through an example.

If I have something like this in my new component:

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

Then I can use my variable inside of the ngOnInit with this. , like so:

this.variable = '1';

But how can I use my variable inside of a child function of the ngOnInit? For example:

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

Thank you.

just use arrow function and you're good as it automatically bind itself to this .

ngOnInit(): void {

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

hope that helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM