Home > Back-end >  Call function that's within ngAfterViewInit from outside ngAfterViewInit
Call function that's within ngAfterViewInit from outside ngAfterViewInit

Time:04-21

As the title suggests, I'm trying to call a function that is within ngAfterViewInit from outside of it. I can't move the function as it uses HTML elements that are only available once ngAfterViewInit has fired.

So, ideally this would work (but it doesn't):

ngAfterViewInit(): void {
  --stuff--
  function foo() {
    --do stuff--
  }
}

public DoSomething() {
  --more stuff--
  foo();
}

CodePudding user response:

If you want to use the this keyword in the function, you'll want an arrow function:

foo?: () => void;

ngAfterViewInit(): void {
  --stuff--
  this.foo = () => {
    //`this` refers to the component
    --do stuff--
  }
}

public DoSomething() {
  --more stuff--
  if (this.foo) this.foo();
}

CodePudding user response:

Make the reference to the function available outside of ngAfterViewInit

@Component()
export class SomeComponent {
 foo: Function;
 
 ngAfterViewInit() {
  // if you need to preserve the 'this' context simply use a lambda instead.
  this.foo = function() {
   // do things.
  }
 }
}
  • Related