angular tutorials

How to call ngOnInit() again from another function – Angular 9 ?

This tutorial guides you on how to call ngOnInit() again from another function in Angular 9. You will also learn the good practices to call ngOnInit() from another function.

Call ngOnInit() again from another function – Angular 9

ngOnInit() is a callback method that will be invoked for the first time right after change detector detecting directive’s data bound properties. And ngOnInit() method will also be invoked right before any of the view child or content child have been checked.

Note, this call back method will be invoked only once when the directive is instantiated. Let’s see more about ngOnInit() method and OnInit lifecycle hook before you learn how to call ngOnInit() from another function.

OnInit lifecycle hook

OnInit lifecycle hook will be called after Angular initializes all data-bound properties of a directive. And if you require any additional initialization tasks, then you need to define an ngOnInit() method to handle the same.

interface OnInit {
  ngOnInit(): void
}

For example, the following code sneppet shows you how to implement the above OnInit interface in a component in order to define its own initialization method.

@Component({selector: 'my-own-component', template: `...`})
class MyOwnComponent implements OnInit {
  ngOnInit() {
    // ...
  }
}

Note, you may try to do the following to call ngOnInit() again from another function. But it is not a good practice.

ngOnInit() {
  //logic
}

anotherMethod(){
  this.ngOnInit();
}

Best practice to call ngOnInit() again ?

I would recommend to implement the “logic” in some other method (someOtherMethod()) and call that method from ngOnInit() and you could call the same method again from another function or method wherever/ whenever needed as shown below.

ngOnInit() {
  this.someOtherMethod();
}

someOtherMethod() {
  //logic
}

anotherMethod() {
  this.someOtherMethod();
}

That’s it. You had learnt whether to call ngOnInit() again in another function or not. And if required to call what is the good practice or alternative option you have for the same.

Hope it helped 🙂

Also See:

References:

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments