Be sure to check out the What is Angular tutorial if you do not know what is Angular.
Be sure to check out the What is Angular tutorial if you do not know what is Angular.
To follow the rest of the tutorial, you will need to know how to setup and start an Angular project. If you do not know yet, visit:
1. A HTML file that structures how our component might look
Creating a component
ng generate component profile
If you are curious of how to open the terminal in VS code, press and hold on the ctrl key and then press the tilde key on the keyboard. The tilde key is located left of the 1 key.
Ctrl + `
Upon completion of the command, expand the app folder in the explorer section of VS code. you will see that a folder is generated with the name you have given the component. Inside that folder, you will see the 3 files – the HTML, CSS, and Class files.
When we use the Angular CLI command – ng generate component, it will generate some boiler plate code, just enough for our component to work. If we look inside the HTML file of our component, there is a paragraph tag with a message.
If we take a look inside, you will see a bunch of HTML code. But what you need to focus on are the <app-root> tags inside the body.
They came from a component. When we generate our project using the ng new command, it will create a component call app. Then it will place that component inside that page so that it will get rendered onto the screen as well.
Next, go to the app component html page and remove all the generated code. Select all the code and delete it. Then add our component inside the page using the angle brackets syntax for adding a html element.
<app-profile></app-profile>
The app component html page is being rendered on the browser because we included it in the index.html page. Since we included our component inside the app component html page, it will also get rendered.
Let’s verify that. Save the project and then start the local server for our project by running the ng serve command on the command prompt or terminal.
ng serve
Once the server is ready, go to localhost:4200 on the browser and we will see a text on the screen.
profile works!
Reusing Components
We can also reuse the component by adding more of it. Go back VS Code and add another component to the application. Add another app-profile tags in the app component html page. Then save and go back to the browser
<app-profile></app-profile>
Now there are 2 lines of text. As you can see, with components, we can break our code into modules that we can then include in our application whenever we need to use it.
Recap