Angular 10 Tutorial - Component

In this tutorial, we will learn about components in Angular 10. Components are the most basic UI building blocks of an Angular application, and an Angular app contains a tree of Angular components.

Angular components are a subset of directives, always associated with a template, and encapsulate the data, logic, and HTML for a view. To work with components, you need to follow three steps:

  • Create a component.
  • Register a component in a Module.
  • Add an element in an HTML markup.

Creating a Component

Let's see how to create a component in Angular 10. Open the command prompt in your project directory and run the command:


ng g c components/user

This will create a new component. The component command creates four files:

  • user.component.css - a CSS file for storing styles for this component.
  • user.component.html - an HTML file for storing the template.
  • user.component.spec.ts - a spec.ts file for writing unit tests for this component.
  • user.component.ts - the actual class component.

Registering the Component

Now, let's switch to the project and go inside the src folder, then app, and finally, the components folder. You will see the four files created earlier. Open the app.module.ts file, and you will see that the user component has been added automatically and also added inside the imports.

Adding Content to the Component

Let's add some text to the user component. Go to the user.component.html file and add a text inside the <h1> tag:


<h1>User Component</h1>

Now, save the file and go to the app.component.html file. Remove all text and add:


<app-user></app-user>

Save the file and run the application by switching to the command prompt and running the command:


ng serve –o

The application will compile, and you will see the user component. If you add more text to the user.component.html file, let's add:


<h2>Angular 10</h2>

Save the file and switch to the browser, and you will see the text. This is how you can create a component in Angular 10.