Skip to content

Create your first component

Chapter objectives

  • ✔️
    Generate a component
    Learn how to create a new component using the Angular CLI.

  • ✔️
    Display the component
    Learn how to display the component's HTML content in the application.

Angular CLI

You’ve already used the CLI to run our application locally with the ng serve command in the Getting Started section. Now use it to create a new component!

The Angular CLI provides a command to generate a new component using ng generate component component-name. You can also use the shorthand command ng g c component-name.

🎓 Instructions

  1. Run the following command in a terminal to generate a new component called task-list

    Terminal window
    ng generate component task-list

    or

    Terminal window
    ng g c task-list
  2. Look for a new folder called task-list in the src/app directory.

Component Metadata

When opening the task-list.component.ts file, you can see the following code:

task-list.component.ts
@Component({
selector: "app-task-list",
templateUrl: "./task-list.component.html",
styleUrls: ["./task-list.component.css"],
})
export class TaskListComponent {}

The @Component decorator defines the component’s configuration metadata. This is where we determine the component context:

The selector property defines the component’s HTML tag name. By using this selector in an HTML Template (view), Angular creates and displays an instance of the component.

The templateUrl property defines the location of the HTML Template (its view) for the component. This is the view that will be displayed when the CSS selector is used in another HTML Template.

The styleUrls property defines the locations of the component’s CSS files. These styles will be applied to the component’s template.

Display the Component

So far, the application only displays the HTML content of the app component in the browser. You’ve generated the new component but you need to display its HTML content using its selector.

🎓 Instructions

  1. Open the src/app/app.component.html file.

  2. Add the task list component selector as follows:

    app.component.html
    <header class="navbar bg-body-tertiary px-4">
    <h1 class="navbar-brand fw-bold">Angular Legacy course</h1>
    </header>
    <main class="container pt-4">
    <app-task-list />
    </main>
  3. Check the changes in your browser.

    A bird sitting on a nest of eggs.

✔️ What you’ve learned

In this chapter, you learned how to create a new component using the Angular CLI and use it in your application.

You also remembered that the component’s view is its HTML Template and the component’s model is its TypeScript file.

🔗 Resources