Which File Executes First in Angular?

Manojkumar
YavarTechWorks
Published in
2 min readOct 2, 2022

Angular can be confusing some times and one of its confusing question is, which file executes first in it. This question haunted me also for quite a long time and I looked up a lot of explanations to understand it. So I thought why not to write an article on this topic so other people can benefit from it.

When we create an angular application we see lots of files like angular.json, package.json, package-lock.json, src folder etc.

When we run ng serve command angular creates a lot of bundles from our source code and use them to render our application on the browser. First it goes to the angular.json file, In this file it uses 2 main properties:

“index”: “src/index.html”

“main”: “src/main.ts”

It loads up main.ts (first file that executes) and read its content. In this file we specify which environment to use for our application and the most important thing, which module to bootstrap, the code is as follows:

platformBrowserDynamic().bootstrapModule(AppModule)

It means that to start our application the first module that is to be loaded (bootstraped) is AppModule. It then reads app.module.ts file.

bootstrap: [AppComponent]

In this file we specify which component to bootstrap, what are all dependencies, etc. It loads only the component specified in bootstrap array and loads it. Here it will load the AppComponent and register this component with its selector name. In app.component.ts we see selector is “app-root”.

When the browser tries to load the application it first loads the index.html. It is a general html file which contains head, body, etc. In this file we see a tag:

<app-root></app-root>

When angular is building our app it inserts all the required scripts to render angular components in index.html file. As we discussed earlier selector of app component was app-root. Browser reads this tag and loads the app-component in place of this tag using the provided scripts.

Conclusion

So when an Angular application is started, the main.ts file is loaded first, here we bootstrap the root module i.e. app.module.ts. In this module, we specify a component as the bootstrap component and tell angular to load this component and all its dependencies at start up and register it’s selector app-root.

Thanks!

--

--