Sub topic 3
Your first standalone component
This chapter builds the first piece of the task list app: a TaskListComponent shown inside the root component. It assumes you can read TypeScript classes and decorators, know what an HTML element and a CSS selector are, and have a project from the earlier chapter, created with ng new task-list. Bindings and @for come in the next chapter, so the list stays empty for now.
What "standalone" means
A component is a TypeScript class that owns a piece of the screen. A decorator called @Component attaches metadata to the class. That metadata tells Angular which HTML tag the component answers to, what it renders, and which other components, directives, and pipes its template may use.
A standalone component declares its own dependencies in its own imports array. Older Angular code grouped components into NgModule classes, and a component could only use what its module declared. Standalone components remove that extra layer. When you read a component file, you can see everything its template depends on.
Standalone is the default in current Angular versions, so you don't write standalone: true. Older tutorials and projects still include it, and it does no harm. If you maintain a project from before Angular 19, a component without that flag may be module-based. Check the version before you copy code.
Generating the component
Run this in the project folder:
ng generate component task-listThe CLI creates a folder with a TypeScript file, a template, a stylesheet, and a spec file. The names depend on the CLI version. Older versions produce task-list.component.ts with a class called TaskListComponent. Recent versions drop the .component suffix from new file names. This tutorial uses the .component.ts names and TaskListComponent. If your CLI generates different names, keep the class name and update the import paths to match your files.
To keep the whole component in one file at first, replace the generated contents with the version below.
Anatomy of the component
import { Component } from '@angular/core';
@Component({
selector: 'app-task-list',
template: `
<h2>My tasks</h2>
<p>Nothing here yet.</p>
`,
styles: `
h2 {
margin-bottom: 0.5rem;
}
`,
})
export class TaskListComponent {}Each metadata property has a job:
| Property | What it does | Notes |
|---|---|---|
| `selector` | The HTML tag that places this component in a template | Prefix it (here `app-`) so it can't clash with real HTML elements |
| `template` | Inline HTML for the view | Use `templateUrl` to point at a separate `.html` file instead |
| `styles` | CSS that applies only to this component | Use `styleUrl` for a separate file; a single string works in current versions |
| `imports` | Standalone components, directives, and pipes the template uses | Each one must be listed here |
Angular scopes component styles by default. The h2 rule above affects only this component's h2 elements, not every h2 on the page. Angular does this by adding generated attributes to the elements and rewriting the CSS selectors. It is the ViewEncapsulation.Emulated setting, and you rarely need to change it.
Inline templates suit small components. Once a template is longer than about 15 lines, a separate templateUrl file is easier to read and gets full HTML editor support.
Using it from the root component
Defining a component does nothing by itself. Angular renders it only when another template contains its selector. The root component AppComponent is the first place to do that.
import { Component } from '@angular/core';
import { TaskListComponent } from './task-list.component';
@Component({
selector: 'app-root',
imports: [TaskListComponent],
template: `
<h1>{{ title }}</h1>
<app-task-list />
`,
})
export class AppComponent {
protected readonly title = 'Task List';
}Three details matter here:
TaskListComponentis imported twice. Theimportstatement is the normal TypeScript module import and makes the class available to the file. Theimportsarray is Angular metadata and makes the class available to the template. You need both.<app-task-list />is a self-closing tag. Angular templates allow this for components, so you don't need a matching</app-task-list>.{{ title }}is interpolation, which prints a class property into the page. Theprotectedmodifier keeps the property out of the public API of the class while still letting the template read it. The next chapter covers bindings in detail.
How the app starts
In a standalone app, main.ts calls bootstrapApplication with the root component and an application config. No root module is involved.
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app/app.component';
import { appConfig } from './app/app.config';
bootstrapApplication(AppComponent, appConfig).catch(err => console.error(err));import { ApplicationConfig } from '@angular/core';
export const appConfig: ApplicationConfig = {
providers: [],
};The providers array in appConfig holds app-wide services. Later chapters add the router and HttpClient there. index.html contains <app-root></app-root>, and Angular replaces that element with the rendered root component.
Start the dev server with ng serve and open http://localhost:4200. You should see the "Task List" heading, then "My tasks" and "Nothing here yet." Edit the template text and save. The page reloads on its own.
Giving the class some data
A component class holds the data and behavior its template uses. To connect this chapter to the typed model from earlier, add a field typed with Task. The field is a placeholder, because the real state moves into signals and a service in later chapters.
import { Component } from '@angular/core';
import { Task } from './task';
@Component({
selector: 'app-task-list',
template: `
<h2>My tasks</h2>
<p>First task: {{ firstTask.title }}</p>
`,
})
export class TaskListComponent {
protected readonly firstTask: Task = { id: 1, title: 'Learn Angular', done: false };
}The compiler now checks the template against the class. If you write {{ firstTask.name }}, the build fails because Task has no name property. Angular's strict template checking is on in new projects. It catches template typos at build time, not in the browser.
Common errors
The mistakes below account for most first-day problems.
- Unknown element. The message
'app-task-list' is not a known element(error code NG8001) means the root template uses the tag, butTaskListComponentis not in theimportsarray. Add it there. Animportstatement at the top of the file is not enough. - Unused import warning. If you add a component to
importsbut never use its tag, current Angular versions warn about it. Remove the unused entry. - Selector typo. The tag in the template must match
selectorexactly.app-tasklistandapp-task-listare different elements, and a mismatch triggers the same unknown element error. - Selector clashes. Without a prefix, a selector like
task-listis easy to confuse with future web components or other libraries. Keep theapp-prefix, which the CLI sets inangular.json. - Forgotten export. If the class isn't declared with
export, theimportin the parent fails with a TypeScript error. - Mixed module code. Don't add standalone components to the
declarationsarray of anNgModule. Doing so raises an error. A standalone component can be listed in a module'simports, which matters only when you work in a mixed codebase.
Checking your work
After this chapter the app should contain TaskListComponent and AppComponent, an appConfig, and a main.ts that bootstraps the root component. The page should show both headings. Run ng build once to confirm the template type checks pass. A clean build means the component wiring is correct, and the next chapter can start adding behavior to the template.
Exercise
You create TaskSummaryComponent with the selector app-task-summary and place <app-task-summary /> in AppComponent's template. The page stays blank and the build reports that app-task-summary is not a known element. The file already has import { TaskSummaryComponent } from './task-summary.component'; at the top. What is missing, and why doesn't the existing import fix it?
Show answer
TaskSummaryComponent must be added to the imports array in AppComponent's @Component metadata. The top-of-file import statement is plain TypeScript. It makes the class available to the file but does not tell Angular's template compiler that the template may use that component. The metadata array does that. After adding imports: [TaskSummaryComponent], the tag resolves and the component renders.
Exercise
Why does the generated TaskListComponent not need standalone: true in its decorator, and when would you still see that flag?
Show answer
In current Angular versions, components are standalone by default, so the flag is redundant. You still see it in projects and tutorials written for Angular 14 to 18, where it was required to opt out of the NgModule system. In those versions, leaving it out made the component module-based.