Angular Components
Angular is a component-based framework, meaning every part of your application (header, footer, form, button, page) is built as a component. Each component contains HTML (template), CSS (styles), and TypeScript (logic).
1. Creating a Component
Use Angular CLI to generate a component quickly:
This creates:
2. Component Decorator
Every component has an @Component decorator, which tells Angular how to handle it.
3. Component Structure
A component has three main parts:
- Template (HTML) – What the user sees
- Styles (CSS/SCSS) – How it looks
- Class (TypeScript) – Logic and data
Example:
home.component.html
home.component.ts
4. Data Binding
Angular provides four ways to bind data between the component class and template.
- Interpolation ( {{ }} )
- Displays data in the template:
- Property Binding ( [ ] )
- Binds values to HTML element properties:
- Event Binding ( ( ) )
- Handles events like click, input, keypress:
- Two-way Binding ( [(ngModel)] )
- Used in forms to bind input values. Requires
FormsModuleimported in your module:
Example:
5. Component Lifecycle Hooks
Angular calls certain methods automatically at specific stages of a component’s life.
Most important hooks:
ngOnInit()– Runs after the component loads (used for API calls)ngOnDestroy()– Runs before the component is destroyed (used to unsubscribe from observables)ngOnChanges()– Runs when input properties changengAfterViewInit()– Runs after the component’s view is initialized
Example:
Summary
- Components are the building blocks of Angular
- Use CLI to create components quickly
@Componentdecorator defines selector, template, and styles- Data binding connects templates and logic: interpolation, property, event, two-way
- Lifecycle hooks help manage initialization and cleanup