What is a Component?
In Angular, a Component is the most fundamental building block of the user interface. It is a self-contained unit that controls a patch of the screen called a 'view'. As an Architect, you should view components as encapsulated modules that combine logic, layout, and styles. This separation ensures that your code remains testable and scalable, similar to the widget-based architecture in Flutter.
- The Three Parts of a Component
Every Angular component consists of three distinct parts that work together to define its behavior and appearance.
- The Component Class: A TypeScript class that handles data and logic (e.g., fetching project details).
- The HTML Template: Defines the visual structure of the component.
- The CSS Styles: Defines the private styles scoped specifically to that component.
- The @Component Decorator
The @Component decorator is a function that identifies the class immediately below it as an Angular component. It provides the Metadata that tells Angular where to find the template and styles, and what selector to use in HTML.
- Component Communication: Input and Output
To build a truly modular system, components must talk to each other. We use the @Input() decorator to pass data from a parent to a child, and the @Output() decorator with an EventEmitter to send data back up.
- Component Lifecycle Hooks
Angular manages the life of a component from creation to destruction. You can 'tap into' specific moments in this lifecycle using Lifecycle Hooks. For a Lead Developer, ngOnInit is the most common place to initialize data or call APIs.
| Hook | Timing | Best For |
|---|---|---|
| ngOnChanges | Before ngOnInit | Responding to @Input() data changes |
| ngOnInit | After first check | Initializing component data / API calls |
| ngAfterViewInit | After view renders | Accessing child DOM elements or ViewChild |
| ngOnDestroy | Just before removal | Cleaning up subscriptions & timers |