In previous blog we created our first application and made some changes in “app.component.ts” to change title on the home page.
We haven’t created any component yet, Instead, we have just made a change in existing component. Now we will create our first component of Angular 6 application and display “Hello World” using the same.
Step 1: Create Home Component
- Open cmd, run the following command in project source folder directory
E:\Workspace\Angular_Repo\ng6-demo>ng generate component Home
- A new component has been created and along with few more few files.
- You may notice that it has generated four files and updated one file “app.module.ts”
- In app.module.ts reference for new component has been included automatically by angular cli.
- Home component has been created in “/src/app/” path.
- This files are part of home component.
Step 2: Change the content in Home Component
- Now that we have our home component generated, lets change the content.
- Replace the content of component.html to
- Now run your application using below command
E:\Workspace\Angular_Repo\ng6-demo>ng serve --open
- Your web page look same as before, why? Because we haven’t included our new component in “app.component”.
- Let’s put our new component in “app.component.html” file
- Open component.ts file, you can see the selector value is “app-home”. Meaning when you put <app-home></app-home> in any other html file it will load home component.
- Open app.component.html file, replace the content with following code
- Now run your app, you can see your changes
Step 3: Understanding the application flow
- What is just happening here? How this application is running and getting our home component display?
- Well for that you need to open index.html file resides in your applications src folder
- There is not much content in this file. Have you noticed <app-root> in <body> tag?
- As I have explained earlier, when we replace the content of app.component.html with <app-home>, it will load the home component.
- Same things is working here, in index.html <app-root> will load the app component. To verify this you can open app.component.ts file and check the selector value.
- So, to summarize when you run your application, index.html page will be called first. Index page has <app-root> included in it. So AppComponent will be loaded. Now in app.component.html file has <app-home> which eventually loads HomeComponent.
You will have good understanding of how angular application works and how to create component. For your exercise you can create one test component and include it in home.component.html and see how it works.
In the next tutorial we will introduce angular material in our application.