Skip to main content
Angular Fundamentals·Lesson 2 of 5

Components & Templates

Components are the building blocks of every Angular app. Each component owns a piece of the UI — its template, its styles, and its logic all live together.

Generating a Component

ng generate component user-card

This creates four files and adds the component to AppModule automatically:

src/app/user-card/
├── user-card.component.ts
├── user-card.component.html
├── user-card.component.css
└── user-card.component.spec.ts

Data Binding

Angular has four binding types:

Interpolation — {{ value }}

Renders a component property as text in the template.

export class UserCardComponent {
  name = 'Sabaoon';
  role = 'Frontend Developer';
}
<h2>{{ name }}</h2>
<p>{{ role }}</p>

Property Binding — [property]="value"

Sets a DOM property from a component property.

<img [src="avatarUrl" [alt="name">
<button [disabled="isLoading">Save</button>

Event Binding — (event)="handler()"

Listens to DOM events and calls a component method.

<button (click="onSave()">Save</button>
<input (input="onSearch($event)">

Two-Way Binding — [(ngModel)]="value"

Syncs the template input and component property in both directions. Requires FormsModule in your module.

<input [(ngModel)="searchQuery" placeholder="Search...">
<p>You typed: {{ searchQuery }}</p>

A Complete Card Component

Here's what a styled user card looks like in the browser — the Angular template would generate this HTML:

Ctrl+Enter
HTML
CSS
JS
Preview

Structural Directives

Angular ships two essential structural directives that manipulate the DOM:

*ngIf — conditionally renders an element:

<div *ngIf="isLoggedIn">Welcome back!</div>
<div *ngIf="!isLoggedIn">Please log in.</div>

*ngFor — renders a list:

<ul>
  <li *ngFor="let user of users; let i= index">
    {{ i + 1 }}. {{ user.name }}
  </li>
</ul>

Component Inputs & Outputs

Pass data into a component with @Input() and emit events up with @Output():

import { Component, Input, Output, EventEmitter } from '@angular/core';

@Component({ selector: 'app-user-card', ... })
export class UserCardComponent {
  @Input() user!: { name: string; role: string }
  @Output() followed = new EventEmitter<string>()

  onFollow() {
    this.followed.emit(this.user.name)
  }
}

Parent template:

<app-user-card
  [user="currentUser"
  (followed="handleFollow($event)">
</app-user-card>