Search code examples
javascriptangulartypescriptangular13

Fetching variables & calling functions from different scope in Angular


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!


Solution

  • 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();
        };
      }
    }