Core Concepts

Components

Create Angular components with decorators, templates, styles, and data binding.

Component Anatomy

An Angular component consists of:

  • Class: Contains the component logic (TypeScript)
  • Template: Defines the view (HTML)
  • Styles: Component-scoped CSS
  • Metadata: The @Component decorator

Data Binding

Angular provides four types of data binding:

  1. Interpolation: {{ value }} — one-way, TypeScript to template
  2. Property binding: [property]="value" — one-way, set HTML properties
  3. Event binding: (event)="handler()" — one-way, listen to events
  4. Two-way binding: [(ngModel)]="value" — bidirectional

Input and Output

Use @Input() to receive data from parent components and @Output() to emit events.

Example

typescript
// user-card.component.ts
import { Component, Input, Output, EventEmitter } from '@angular/core';
import { CommonModule } from '@angular/common';

interface User {
  id: number;
  name: string;
  email: string;
  avatar: string;
}

@Component({
  selector: 'app-user-card',
  standalone: true,
  imports: [CommonModule],
  template: `
    <div class="card" [class.highlighted]="isHighlighted">
      <img [src]="user.avatar" [alt]="user.name" />
      <h3>{{ user.name }}</h3>
      <p>{{ user.email }}</p>
      <button (click)="onFollow()">
        {{ isFollowing ? 'Unfollow' : 'Follow' }}
      </button>
    </div>
  `,
})
export class UserCardComponent {
  @Input() user!: User;
  @Input() isHighlighted = false;
  @Output() follow = new EventEmitter<number>();

  isFollowing = false;

  onFollow() {
    this.isFollowing = !this.isFollowing;
    this.follow.emit(this.user.id);
  }
}

// Parent component using UserCard
@Component({
  template: `
    <app-user-card
      [user]="currentUser"
      [isHighlighted]="true"
      (follow)="handleFollow($event)"
    />
  `
})
export class ParentComponent {
  currentUser = { id: 1, name: 'Alice', email: 'alice@example.com', avatar: '' };
  handleFollow(userId: number) { console.log('Following user:', userId); }
}
Try it yourself — TYPESCRIPT