Components
An Angular app is made of components. A component is a TypeScript class with the @Component decorator. It has a selector (its tag name), a template (its HTML) and optional styles.
Just like in React, an Angular page is built from components - header, product list, product card, footer. Each component bundles three things: the class (data and logic in TypeScript), the template (HTML) and the styles (CSS, which only apply to that component, so styles don't leak into the rest of the app).
The @Component decorator is metadata that tells Angular: "this class is a component, use it wherever you see the tag <app-product-card>, and here is its HTML". The app- prefix on selectors is a convention that keeps your tags from clashing with real HTML tags.
import { Component } from '@angular/core';
@Component({
selector: 'app-product-card',
template: '<h3>Wireless Headphones</h3><p>Rs 1,299</p>',
styles: 'h3 { color: purple; }',
})
export class ProductCard {}Use it in another component's template like an HTML tag, and add the class to that component's imports list:
import { Component } from '@angular/core';
import { ProductCard } from './product-card';
@Component({
selector: 'app-root',
imports: [ProductCard],
template: '<h1>Today\'s deals</h1> <app-product-card />',
})
export class App {}The CLI can create a component for you: ng generate component product-card.
imports, with no extra modules needed.- A component = TypeScript class + template + styles.
- The selector is its HTML tag; add it to
importswhere it's used. - Create components with
ng generate component name.
