Anatomy of an Angular Component: Template, Styles, and Logic
In the Angular ecosystem, the **Component** is the fundamental building block of the user interface. While a simple website might use disjointed HTML and JS files, Angular enforces a strict, modular structure where each part of the UI is a self-contained unit consisting of three key elements: Structure (Template), Appearance (Styles), and Behavior (Logic).
1. The Logic (TypeScript)
The brain of the component is a TypeScript class. This is where you define the state of your UI (variables) and the behavior (functions). By itself, it's just a class; it becomes a component only when adorned with the `@Component` decorator.
export class UserProfileComponent {
username: string = "DevOne";
logout() {
console.log("User logged out");
}
}2. The Template (HTML)
The template is the face of your component. It looks like standard HTML, but with superpowers. Through **Interpolation** ({{ variable }}), you can inject data directly from your TypeScript logic into the view. Through **Directives**, you can modify the DOM dynamically.
You can define templates inline for small components or in external files for complex ones:
- Inline: `template: '<h1>Hello</h1>'`
- External: `templateUrl: './app.component.html'`
3. The Styles (CSS/SCSS)
One of Angular's most powerful features is **View Encapsulation**. When you define styles for a component (using `styleUrls`), those styles are scoped only to that component.
Note: If you write `h1 { color: red; } in a component's CSS file, it will NOT affect `h1` tags in other components. This prevents the "CSS bleeding" issues common in traditional web development.
Putting It All Together
The **Metadata** (provided by the decorator) is what links these three files together into a cohesive unit. It tells Angular: "This class uses this HTML file and this CSS file."