Angular Tutorial
Angular Components Fundamentals
Components are the primary building blocks of an Angular application. Every single piece of user interface you see on screen—whether it's a Navbar, a Button, or an entire Login Form—is an Angular Component.
What is a Component?
In plain terms, a Component is simply a TypeScript class equipped with a special decorator called @Component. This decorator tells Angular exactly how to render the class as a piece of UI, attaching an HTML template and CSS styles to it.
An Angular Component consists of three main parts conceptually:
- The Class (TypeScript): Holds data properties and UI logic (methods).
- The Template (HTML): Dictates how it looks on screen.
- The Styles (CSS/SCSS): Dictates the colors and visual layout, scoped specifically only to this component.
Creating a Component via CLI
You should almost never write a Component entirely from scratch. The Angular CLI generates the boilerplate for you:
ng generate component header
# or shortened:
ng g c headerThis command automatically creates a folder named header/ and generates 4 files (ts class, html template, css styles, and basic spec test).
The @Component Decorator Breakdown
Let's look at a basic Component class:
import { Component } from '@angular/core';
@Component({
selector: 'app-header',
standalone: true,
templateUrl: './header.component.html',
styleUrls: ['./header.component.css']
})
export class HeaderComponent {
// Class logic lives here
siteTitle: string = "HiFi Toolkit";
changeTitle() {
this.siteTitle = "New Title!";
}
}1. selector
The selector is the custom HTML tag you use to render this Component in other parts of your app. Because the selector above is app-header, we can use it inside our main HTML file like this:<app-header></app-header>.
2. standalone: true
Introduced in Angular 14, this signifies that the component does NOT require an older NgModule to function. It is entirely self-sufficient, making modern Angular much easier to learn.
3. templateUrl & styleUrls
These point to the external HTML and CSS files physically linked to this Component class. Alternatively, you can write inline HTML strings using template: \`<h1>Hi</h1>\` for very short components.
Component Lifecycle
Components are created, updated, and destroyed by Angular. As this happens, Angular triggers specific methods called Lifecycle Hooks. The most important hook is ngOnInit(), which runs once right after the component is initialized, perfect for fetching API data!
Conclusion
Now that we have created a TypeScript class linked to an HTML template, how do we get the data from our class to actually show up dynamically in that HTML? We do that using Templates & Data Binding.