Components
A component is Angular's basic building block: a TypeScript class that holds data and behavior, paired with an HTML template that says how to display it.
Anatomy of a component
The @Component decorator is what turns a plain class into something Angular recognizes and can render:
import { Component } from '@angular/core';
@Component({
selector: 'app-greeting',
template: `<h2>Hello, {{ name }}!</h2>`
})
export class GreetingComponent {
name = 'Priya';
}
<h2>Hello, Priya!</h2>
selector is the custom HTML tag this component becomes — <app-greeting></app-greeting> anywhere in another template renders this one. template holds the HTML (here inline as a string; larger components usually put it in a separate .html file instead, referenced with templateUrl). The class body — name = 'Priya' — is exactly what the template's {{ name }} reads from.
Splitting template and styles into their own files
The CLI's default generator produces three files per component rather than one inline string, which is the more common real-world shape:
import { Component } from '@angular/core';
@Component({
selector: 'app-greeting',
templateUrl: './greeting.component.html',
styleUrl: './greeting.component.css'
})
export class GreetingComponent {
name = 'Priya';
}
<h2>Hello, {{ name }}!</h2>
Same result as before — this is purely an organizational choice, and the one you'll see in almost every real Angular codebase once a template grows past a line or two.
Nesting components
A component's selector can be used inside another component's template, exactly like a regular HTML tag:
<h1>My App</h1> <app-greeting></app-greeting>
<h1>My App</h1> <h2>Hello, Priya!</h2>
This is how an Angular application is actually built: a handful of small components, each responsible for one piece of the page, composed together inside larger ones.
imports array in its @Component decorator. Forgetting this import is one of the most common beginner errors, and it shows up as the custom tag rendering as empty/unrecognized HTML rather than a clear compiler error.