Sub topic 8
Building Your First Component
A component is the basic building block of an Angular user interface. Each component pairs a TypeScript class with a template and optional styles, and Angular renders it wherever its selector appears in a parent template. This chapter covers how a component is put together, how to generate one with the CLI, how to use it inside another component, and the mistakes intermediate developers make most often.
This chapter assumes you have a project created with ng new, can run ng serve, and know where main.ts and the root App component live. You should also be comfortable with TypeScript classes and decorator syntax. Binding syntax, signals, inputs and outputs each get their own chapter later. This chapter uses only simple interpolation ({{ value }}) so the focus stays on the component itself.
Anatomy of a Component
A component is a class decorated with @Component. The decorator's metadata object tells Angular how to create and render the component.
// src/app/profile-card/profile-card.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-profile-card',
templateUrl: './profile-card.html',
styleUrl: './profile-card.css',
})
export class ProfileCard {
name = 'Ada Lovelace';
role = 'Engineer';
}The template file holds the component's HTML:
<!-- src/app/profile-card/profile-card.html -->
<article class="card">
<h2>{{ name }}</h2>
<p>{{ role }}</p>
</article>The stylesheet applies only to this component (more on this under view encapsulation):
/* src/app/profile-card/profile-card.css */
:host {
display: block;
margin-bottom: 1rem;
}
.card {
border: 1px solid #ccc;
border-radius: 8px;
padding: 1rem;
}These are the metadata properties you will use most:
| Property | Purpose | Notes |
|---|---|---|
| `selector` | The CSS selector that marks where the component renders | Usually an element name with a prefix, such as `app-profile-card` |
| `template` | Inline HTML template | Cannot be combined with `templateUrl` |
| `templateUrl` | Path to an external HTML file, relative to the `.ts` file | Generated by default with the CLI |
| `styles` | Inline CSS, as a string or an array of strings | Good for small components |
| `styleUrl` / `styleUrls` | Path or paths to external stylesheets | `styleUrl` (singular) is available from Angular 17 |
| `imports` | Components, directives and pipes this template uses | Required for every child component you place in the template |
| `encapsulation` | How styles are scoped | Defaults to `ViewEncapsulation.Emulated` |
Standalone by default
Since Angular 19, components are standalone by default. A standalone component declares its own template dependencies in imports and does not need an NgModule. In Angular 14 to 18 you had to write standalone: true yourself. Older module-based code marks components with standalone: false and declares them in an NgModule. If you read tutorials from before 2024, expect to see both styles.
Generating a Component with the CLI
Writing the files by hand works, but the CLI creates them with consistent naming and a test file:
ng generate component profile-cardThe short form is ng g c profile-card. In a project created with Angular 20 or later, this produces:
src/app/profile-card/profile-card.ts
src/app/profile-card/profile-card.html
src/app/profile-card/profile-card.css
src/app/profile-card/profile-card.spec.tsProjects from earlier CLI versions use the older naming style: profile-card.component.ts with a class named ProfileCardComponent. Both styles work. Pick the one your workspace already uses and stick to it.
These flags come up often:
| Flag | Effect |
|---|---|
| `--inline-template` (`-t`) | Puts the template in the `.ts` file instead of a separate `.html` |
| `--inline-style` (`-s`) | Puts styles in the `.ts` file |
| `--skip-tests` | Does not create the `.spec.ts` file |
| `--flat` | Creates the files directly in the current folder without a subfolder |
| `--dry-run` | Shows what would be created without writing anything |
Using a Component in a Parent
A component appears on screen only when another component's template uses its selector, or when it is the root component passed to bootstrapApplication. To render ProfileCard inside the root component, import the class in TypeScript and also list it in the decorator's imports array:
// src/app/app.ts
import { Component } from '@angular/core';
import { ProfileCard } from './profile-card/profile-card';
@Component({
selector: 'app-root',
imports: [ProfileCard],
template: `
<h1>Team</h1>
<app-profile-card />
<app-profile-card />
`,
})
export class App {}Each <app-profile-card /> tag creates its own instance of the class with its own fields. Angular has supported self-closing component tags since version 15.1. Older code writes <app-profile-card></app-profile-card>.
The two imports are different things
The TypeScript import statement at the top of the file makes the class available to the module system. The imports array in @Component tells the Angular compiler that this template may use the class. If you leave out the TypeScript import, TypeScript reports an error. If you leave out the decorator entry, Angular fails at compile time with:
NG8001: 'app-profile-card' is not a known elementThis is the error intermediate developers hit most often when they start working with standalone components.
Selectors and Naming
Angular's style guide uses kebab-case element selectors with a short prefix. The CLI applies the app prefix by default, and you can change it in angular.json under the project's prefix setting. The prefix keeps your elements from clashing with native HTML elements and with third-party libraries. A custom element name must contain a hyphen, so card alone is not a safe choice.
Selectors can also be attribute selectors ([appHighlight]) or class selectors. Use those mainly for directives. Components almost always use element selectors because a component owns its own block of DOM.
View Encapsulation
By default, Angular scopes a component's styles to that component. In the default Emulated mode, the compiler adds generated attributes such as _ngcontent-abc-c12 to the component's elements and rewrites the CSS selectors to match them. A .card rule in profile-card.css therefore does not leak into other components.
| Mode | Behavior | When to use |
|---|---|---|
| `Emulated` (default) | Styles scoped with generated attributes | Almost always |
| `ShadowDom` | Uses the browser's native Shadow DOM | When you want true isolation, for example in web components |
| `None` | Styles become global | Rarely, for deliberate global theming |
The :host selector targets the component's own host element (<app-profile-card>). Custom elements are display: inline by default, so setting display: block on :host is a common fix when margins or widths seem to have no effect.
import { Component, ViewEncapsulation } from '@angular/core';
@Component({
selector: 'app-global-banner',
template: `<div class="banner">Maintenance tonight</div>`,
styles: `.banner { background: gold; padding: 0.5rem; }`,
encapsulation: ViewEncapsulation.None,
})
export class GlobalBanner {}With None, the .banner rule applies to every element with that class across the app. That is why this mode is risky.
Lifecycle Basics
Angular creates the class instance, renders its template, and eventually destroys it. You can hook into these stages:
import { Component, OnDestroy, OnInit } from '@angular/core';
@Component({
selector: 'app-clock',
template: `<p>{{ now }}</p>`,
})
export class Clock implements OnInit, OnDestroy {
now = new Date().toLocaleTimeString();
private timerId?: ReturnType<typeof setInterval>;
ngOnInit() {
this.timerId = setInterval(() => {
this.now = new Date().toLocaleTimeString();
}, 1000);
}
ngOnDestroy() {
clearInterval(this.timerId);
}
}Keep the constructor for simple field setup and dependency injection. Put work that depends on inputs in ngOnInit, because inputs are not yet set when the constructor runs. Always clean up timers and subscriptions in ngOnDestroy. Otherwise they keep running after the component leaves the page, which causes memory leaks and errors from work done for a component that no longer exists.
Common Errors and Their Causes
| Symptom | Likely cause | Fix |
|---|---|---|
| `NG8001: ... is not a known element` | Child component missing from `imports` | Add the class to the parent's `imports` array |
| Component tag renders nothing and shows no error | Selector typo matched no component, so the browser treats the tag as an unknown element | Compare the selector with the tag character by character |
| Styles have no visible effect on layout | Host element is inline by default | Add `:host { display: block; }` |
| Error about `template` and `templateUrl` | Both properties set | Keep only one |
| Template file not found at build time | `templateUrl` path is wrong | Paths are relative to the `.ts` file, so start with `./` |
| Component appears in some places but not others | Imported in only one parent | Each parent template that uses it must import it |
Exercise
You generate a component named user-badge in an Angular 20 project and place <app-user-badge /> in App's template. The build fails with NG8001. You have already added import { UserBadge } from './user-badge/user-badge'; at the top of app.ts. What is missing, and why is the TypeScript import not enough?
Show answer
UserBadge must also be listed in the imports array of App's @Component decorator. The TypeScript import only makes the class available to the module system. The decorator's imports array is what tells the Angular compiler that the template is allowed to use the app-user-badge selector.
Exercise
You set margin-bottom: 2rem on :host in a component's stylesheet, but the components still sit side by side with no space between them. What is the cause, and what one-line change fixes it?
Show answer
The host element is a custom element, and custom elements are display: inline by default. Vertical margins do not push inline elements apart the way they push block elements apart. Adding display: block; to the :host rule makes each host element a block, so the margin applies and the components stack vertically.
Exercise
A component starts a setInterval in ngOnInit. After the user navigates away and back several times, the app slows down. Explain the cause and the fix.
Show answer
Each visit creates a new component instance and starts a new interval, but the old intervals are never cleared, so they keep running after their components are destroyed. Implement OnDestroy and call clearInterval with the stored timer ID in ngOnDestroy.