Angular Components: an overview
An Angular app is a tree of components. Each component is a small, reusable piece of the page, made of a TypeScript class for its data and behavior, an HTML template for how it looks, and its own styles.
Novice · Angular · Updated
After this lesson you can
- Explain what a component is, and break a page into components
Key takeaways
- An Angular app is a tree of components with
Appat the root, and the same component, such asProductCard, can appear many times. - A component has three parts: a class for its data and behavior, a template for its HTML, and its own styles.
- A component's styles are scoped: they change only that component's elements, so components can't break each other's looks.
- Break a page into small components that each do one job, so each is easy to understand, change, test and reuse.
Look at any web page and you can see its pieces: a header, a menu, a list of products, each product a card, each card with a button. In Angular, each of those pieces is a component.
A tree of components
A component can contain other components, so an app is a tree:
App
├── Header
├── CategoryMenu
└── ProductList
├── ProductCard
├── ProductCard
└── ProductCard
└── AddToCartButton
App is the root, started by main.ts. Everything else is inside it, at any depth. The same component can appear many times, like ProductCard here, each showing a different product.
What a component is made of
Each component has three parts, usually in three files:
| Part | File | Holds | Like in MVC |
|---|---|---|---|
| A class | product-card.ts |
The component's data and what it does | A view model and its actions |
| A template | product-card.html |
Its HTML, showing the data | A Razor view |
| Styles | product-card.css |
CSS for this component only | Scoped CSS, like _Layout.cshtml.css |
The styles are scoped: a rule such as h2 { color: maroon; } in product-card.css changes only the product card's h2s, never any other component's. So components can't break each other's looks.
Why components?
- Reuse. Write
ProductCardonce, and show it for every product, on every page that needs one. - Small pieces. Each component does one job, so it's easy to understand, change and test, like the small classes you've written all along.
- Teamwork. Different people can build different components at the same time.
You've already met the idea: a partial view such as _ProductCard.cshtml was a reusable piece of a page. A component is that idea taken all the way: every part of the page is one, with its own data and behavior, and it runs in the browser.
Check yourself
1 question to try on the lesson page.
So what
Think of a page as a tree of small, single-purpose pieces. In Angular, every piece is a component: a class, a template and styles, used as often as you like.