Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Components

A component is a self-contained piece of the interface: a header, a card, a to-do list. An Angular application is assembled from components like building blocks: one component renders others inside it.

The component class

In the previous lesson the command ng generate component todo-list created the file src/app/todo-list/todo-list.ts:

// src/app/todo-list/todo-list.ts
import { Component } from '@angular/core';
 
@Component({
  selector: 'app-todo-list',
  imports: [],
  templateUrl: './todo-list.html',
  styleUrl: './todo-list.css',
})
export class TodoList {
  title = 'My tasks';
}

The @Component decorator describes the component, and the class holds its data and methods. The title field is available in the template.

SettingMeaning
selectorThe tag name used to insert the component into a template
importsComponents and directives used in the template
templateUrlThe template file
styleUrlThe stylesheet file

All components in modern Angular are standalone: each one lists what it needs in imports.

The template

The template is the component's HTML:

<!-- src/app/todo-list/todo-list.html -->
<section>
  <h2>{{ title }}</h2>
  <p>No tasks yet.</p>
</section>

Double curly braces output the value of a class field — more on them in the next lesson.

Styles

/* src/app/todo-list/todo-list.css */
section {
  max-width: 400px;
  padding: 16px;
  border: 1px solid #ddd;
}

A component's styles apply only to its own template. The section rule will not affect other sections on the page.

How to render a component

The TodoList component appears on the page only if its tag is in another component's template. Add it to App:

// src/app/app.ts
import { Component } from '@angular/core';
import { TodoList } from './todo-list/todo-list';
 
@Component({
  selector: 'app-root',
  imports: [TodoList],
  templateUrl: './app.html',
  styleUrl: './app.css',
})
export class App {}
<!-- src/app/app.html -->
<h1>To-do list</h1>
<app-todo-list />

Open http://localhost:4200: under the heading a box appears with "My tasks" and "No tasks yet." The tag can be self-closing, as here.

Inline template

A short template can be written right in the decorator — the template property instead of templateUrl, and styles instead of styleUrl:

// src/app/badge/badge.ts
import { Component } from '@angular/core';
 
@Component({
  selector: 'app-badge',
  template: `<span class="badge">new</span>`,
  styles: `.badge { color: green; }`,
})
export class Badge {}

This is handy for small components of a few lines.

Common mistake

If you put <app-todo-list /> in a template but forget to add TodoList to imports, the build stops with an error like 'app-todo-list' is not a known element. Every component whose tag appears in a template must be imported in TypeScript and listed in imports.

Thanks for reading!

Donate to the site — we work hard for you.