VKP
VKP

Reputation: 658

How to call body onload JavaScript functions in Angular 10

We are migrating old JavaScript projects into Angular 10. There are many JavaScript functions calling from body onload. What is the best way to call such functions in Angular 10? Please help.

Upvotes: 1

Views: 1303

Answers (2)

Siraj Ali
Siraj Ali

Reputation: 604

In Angular 10 you can call a javascript function on body load using ngOnInit() function

call the the function inside the ngOnInit() function .

like this

export class DashboardComponent implements OnInit {

constructor() {}

ngOnInit(): void {
  this.checkNotifiactionToken(); //this is your custom function which is you want to call on body load
}
}

Upvotes: 2

Abhinav Kumar
Abhinav Kumar

Reputation: 3036

There should be a specific approach, when you are migrating old js body onload function. And you have multiple functions as well.

To keep it in mind angular component solution, I would suggest 1st to find which are the function required for which components.

let's suppose you have five function are in body onload.

One function required before even loading the app to get some configuration, move it to app initializer, you need to setup APP_INITIALIZER in angular.

Other two function required to load the 1st paint or home page. Move them to their respective components or you can use route resolver, if you have routing or ngOninit

The key point here to for better performance, in Angular we have multiple way to do it. You need to find that match where things required and fit.

Upvotes: 2

Related Questions