Components: Class + Template + Selector
A component is three things working together — a class for data, a template for HTML, and a selector that places it on the page.
What you will learn
- Describe the three parts of a component
- Generate a component with the CLI
- Use a component by its selector tag
The building block of every Angular app
Everything you see in an Angular app is a component. Each component bundles three parts:
- Class — the TypeScript that holds the data and logic.
- Template — the HTML that gets shown on screen.
- Selector — a custom tag name used to place the component, like
<app-greeting>.
Generate one with the CLI
You rarely write a component by hand. Ask the CLI to make it for you:
ng generate component greeting
# short form: ng g c greetingNote: Output: CREATE src/app/greeting/greeting.component.ts CREATE src/app/greeting/greeting.component.html CREATE src/app/greeting/greeting.component.css You get the class, the template and a stylesheet, all wired together for you.
What a component looks like
Here is a small component. The @Component decorator is a label that tells Angular the selector and which template to use. The class below it holds the data.
// src/app/greeting/greeting.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-greeting',
template: '<h2>Hello, {{ name }}!</h2>'
})
export class GreetingComponent {
name = 'Asha'; // data the template can show
}Note: Output (when used on a page):
Hello, Asha!
The selector app-greeting marks where it appears; the template is the HTML; the class supplies name. The double curly braces print the value (next lesson).
Use it by its selector
To show the component, drop its selector tag into another component’s template — for example the root component:
<!-- src/app/app.component.html -->
<h1>My App</h1>
<app-greeting></app-greeting>Note: Output:
My App
Hello, Asha!
Angular replaces <app-greeting> with the component’s template. You can reuse that tag as many times as you like.
Tip: The CLI prefixes selectors with app- by default (like app-greeting). This keeps your tags from clashing with real HTML tags.
Q. Which three parts make up an Angular component?
✍️ Practice
- Generate a
greetingcomponent withng g c greetingand look at the files created. - Show your component on the page by adding its selector to
app.component.html.
🏠 Homework
- Create a
profile-cardcomponent with anameand aroleproperty, and display it in the app.