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:
Are variables or function defined in the component not public by default?
Thanks in advance!
CodePudding user response:
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();
};
}
}