0

I have a local function say, compulsoryFunction() inside ngOnInit() which is triggered automatically by a library I'm using. I am bound to have it as a local function inside ngOnInit.

Problem - I am unable to access variables or call functions declared in that angular Component.

    export class MyComponent implements OnInit {
    message= "Hello";
    OuterFunction(){
      console.log("Outer Function called");
    }
    ngOnInit(): void { 
    console.log('msg0: ',this.message);  
    function  compulsoryFunction() {
    console.log('msg: ',this.message);
    this.OuterFunction();
    }

The error is as follows:

enter image description here

Are variables or function defined in the component not public by default?

Thanks in advance!

Swapnil Sourabh
  • 459
  • 4
  • 17
  • In typescript you **not** use `function nameOfFunction(){...}`, and you can not defined a function inside another function. And yes, by defect all the variables and functions are public. you use `functionName(...){...}` and `this.functionName()`to call it – Eliseo Dec 13 '21 at 18:42
  • 1
    In typescript, we can have nested functions. Its not a limitation. – Swapnil Sourabh Dec 13 '21 at 20:19
  • 1
    then use arrow flat to get the "this" – Eliseo Dec 13 '21 at 20:25

1 Answers1

1

You can change the this context using arrow functions.

export class MyComponent implements OnInit {
  message = 'Hello';

  OuterFunction() {
    console.log('Outer Function called');
  }

  ngOnInit() {
    console.log('msg0: ', this.message);

    const compulsoryFunction = () => {
      console.log('msg: ', this.message);
      this.OuterFunction();
    };
  }
}