Video lecture
Watch on YouTube(opens in a new tab)Sub topic 1
What a Component Is: Decorator, Selector, Template, and Class
An Angular application is a tree of components. Each component controls one rectangle of the screen: a header, a search box, a row in a list. This chapter takes a single component apart so you know what each piece does, how Angular connects the pieces, and which mistakes cause the most common early errors.
Prerequisites
This chapter assumes you are comfortable with:
- HTML and CSS fundamentals
- JavaScript ES2015+ syntax, especially classes and modules
- Basic TypeScript, including types and classes
- Running npm commands in a terminal
- The general idea of the DOM
The examples target Angular 19 or later, where components are standalone by default. You can follow along in a project created with npx @angular/cli new my-app.
The Four Parts of a Component
A component is a TypeScript class with metadata attached. The metadata tells Angular how to render the class and where to put it. The four parts are:
| Part | Where it lives | What it does |
|---|---|---|
| Class | `export class ...` | Holds the state and behavior that the template reads and calls |
| `@Component` decorator | Directly above the class | Attaches metadata and marks the class as a component |
| Selector | `selector` in the decorator | Tells Angular which HTML elements should become instances of this component |
| Template | `template` or `templateUrl` | Defines the DOM that Angular renders inside the matched element |
Styles (styles or styleUrl) are optional, but nearly every component has them.
A Complete, Runnable Component
Here is the smallest useful component, plus the code that starts the application.
// src/app/greeting.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-greeting',
template: `
<h1>Hello, {{ name }}!</h1>
<p>You have {{ unread }} unread messages.</p>
`,
styles: `h1 { color: steelblue; }`,
})
export class GreetingComponent {
name = 'Ada';
unread = 3;
}// src/main.ts
import { bootstrapApplication } from '@angular/platform-browser';
import { GreetingComponent } from './app/greeting.component';
bootstrapApplication(GreetingComponent).catch((err) => console.error(err));<!-- src/index.html -->
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Greeting</title>
</head>
<body>
<app-greeting></app-greeting>
</body>
</html>When you run ng serve, Angular finds <app-greeting> in index.html, creates one GreetingComponent instance, and renders the template inside that element. The {{ name }} syntax displays a class property. Interpolation gets its own chapter, so for now just note that the template can read public members of the class.
How Angular Wires the Parts Together
Angular compiles templates ahead of time. The compiler turns your template string into JavaScript instructions that create and update DOM nodes. Two things follow from this:
- Template syntax errors, such as an unclosed tag or a reference to a property that does not exist, show up at build time, not in the browser.
- The template must be known statically. You cannot build a template string at runtime and hand it to
@Component.
The element that matches the selector is called the host element. It belongs to the parent's template (or to index.html for the root component). Your component's template is rendered inside the host element, not in place of it. If you inspect the page, you will see <app-greeting> wrapping the <h1> and <p>.
The Class
The class is ordinary TypeScript. Angular creates one instance for every host element it matches, so two <app-greeting> tags give you two independent instances with separate state.
Keep these rules in mind:
- The template can only use members the class exposes. Members marked
privateare not accessible from the template and cause a compile error. Useprotectedif you want a member visible to the template but not part of the public API. - Angular calls the constructor itself. Never write
new GreetingComponent()to put a component on screen. - Keep the constructor light. Inputs from a parent have not been set yet when it runs. Later chapters on inputs and lifecycle hooks explain when they are set.
The Selector
The selector is a CSS selector. Angular supports a subset of CSS:
| Selector form | Example | Matches |
|---|---|---|
| Element | `app-greeting` | `<app-greeting>` |
| Attribute | `[appGreeting]` | `<div appGreeting>` |
| Element plus attribute | `button[appPrimary]` | `<button appPrimary>` only |
| Class | `.app-greeting` | `<div class="app-greeting">` |
Element selectors are the norm for components. Attribute selectors make sense when the host should stay a native element, such as a <button> that keeps its built-in keyboard and accessibility behavior:
import { Component } from '@angular/core';
@Component({
selector: 'button[appPrimary]',
template: `<ng-content />`,
styles: `:host { background: steelblue; color: white; }`,
})
export class PrimaryButtonComponent {}
// Usage: <button appPrimary>Save</button>The <ng-content /> and :host pieces are covered in later chapters. Here they just let the button show its label and receive styling.
Naming conventions matter in practice:
- Use a prefix (
app-by default, set inangular.json) so your elements never clash with future HTML elements or third-party libraries. - Include a hyphen in element selectors. Custom element names in HTML must contain one, and it makes Angular elements easy to spot in templates.
- Only one component can match a given element. If two components' selectors match the same element, the compiler reports an error.
The Template
You can write the template inline or in a separate file:
import { Component } from '@angular/core';
@Component({
selector: 'app-profile',
templateUrl: './profile.component.html',
styleUrl: './profile.component.css',
})
export class ProfileComponent {
displayName = 'Grace';
}Inline templates suit small components because you see the markup and logic together. Separate files work better once the template grows past a screenful, and editors give better HTML support in .html files. The CLI generates separate files by default (ng generate component profile).
Templates are mostly plain HTML with some exceptions. <script> tags are stripped for security. Template syntax such as {{ }}, [ ], ( ), and @if is added on top of HTML, and the rest of this tutorial covers it.
Common Errors
| Error message (abridged) | Usual cause | Fix |
|---|---|---|
| `NG8001: 'app-x' is not a known element` | The parent does not import the child, or the selector is misspelled | Add the child to the parent's `imports` array and check the selector |
| `Property 'x' does not exist on type 'MyComponent'` | The template references a missing or misspelled member | Add or rename the class property |
| `Property 'x' is private and only accessible within class` | A `private` member is used in the template | Make it `protected` or `public` |
| Blank page, no error | The root selector does not match the tag in `index.html` | Make the two names identical |
The first error is the most frequent one, and the next chapter on the imports array explains it fully.
Exercises
Exercise
You place <app-greeting></app-greeting> twice in a parent template and change name in one instance. What happens to the other one, and why?
Show answer
Nothing changes in the other one. Angular creates a separate class instance for each host element that matches the selector, so each instance has its own name property.
Exercise
A component uses selector: 'a[appExternalLink]'. Which of these elements become instances of it: <a appExternalLink>, <button appExternalLink>, <a>?
Show answer
Only <a appExternalLink>. The selector requires both the a element and the appExternalLink attribute, so the button and the plain anchor do not match.
Exercise
Your template uses {{ secret }} and the class declares private secret = 'x';. The build fails. Give a fix that keeps secret out of the component's public API.
Show answer
Declare it as protected secret = 'x';. Protected members are accessible from the template but are not visible to outside code that holds a reference to the component.
Exercise
Write a component with selector app-clock that shows the text "Current year: " followed by a year property set to the current year, with the year styled in bold.
Show answer
import { Component } from '@angular/core'; @Component({ selector: 'app-clock', template: <p>Current year: <strong>{{ year }}</strong></p>, styles: strong { font-weight: bold; } }) export class ClockComponent { year = new Date().getFullYear(); }