Angular FAQ: Top Questions
2. What is a Component in Angular?
A Component in Angular is the core building block of an Angular application. Each component encapsulates three key parts:
- Template (HTML): Defines the structure and layout of the UI.
- Class (TypeScript): Contains the business logic, methods, and properties that drive the view.
- Styles (CSS/SCSS): Applies styling to the component’s view.
Components are responsible for rendering views and reacting to user input. Every Angular application must have at least one component — the root component (AppComponent
) — from which all other components branch out in a hierarchical structure.
-
Selector:
- A custom HTML tag defined by the component that determines where it should appear in the DOM.
-
Example:
<app-user></app-user>
-
Template:
-
HTML markup that defines the component’s visual structure and binds to the class using Angular syntax like
{{ }}
or[property]
.
-
HTML markup that defines the component’s visual structure and binds to the class using Angular syntax like
-
Class:
- A TypeScript class where properties and methods are defined.
- Provides the logic behind the template — for example, handling events, calculations, or service calls.
-
Metadata:
-
Angular uses the
@Component
decorator to associate the class with its template, styles, and selector.
-
Angular uses the
// user.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-user',
template: '<p>User: {{ name }}</p>',
styles: ['p { font-weight: bold; }']
})
export class UserComponent {
name: string = 'Alice';
}
Explanation of the Example Code:
@Component
defines the metadata for the component, including the selector, template, and styles.selector: 'app-user'
means this component can be used in HTML as<app-user></app-user>
.template
uses Angular’s interpolation syntax{{ name }}
to display the value of thename
property.- When the
name
value changes, Angular’s change detection updates the DOM automatically.
Components make it easy to encapsulate logic and UI together, supporting code reuse, modularity, and testability. In a large Angular application, dozens or even hundreds of components work together to form a complete user interface.