Skip to content

Angular 치트시트

Google이 만든 TypeScript 기반 웹 애플리케이션 프레임워크입니다.

01

시작하기

CLI 설정과 프로젝트 생성

Angular CLI는 개발의 기본 도구입니다. ng new는 라우팅과 스타일이 미리 설정된 완전한 프로젝트를 스캐폴딩해 줍니다. 일관된 파일 생성을 위해 ng generate(ng g)를 사용하세요. 빌드, 테스트, 배포도 CLI가 처리합니다.

angular
# install Angular CLI globally
npm install -g @angular/cli

# create a new project
ng new my-app --routing --style=scss
cd my-app

# serve the app (default: localhost:4200)
ng serve --open

# generate components, services, etc.
ng generate component components/user-profile
ng g service services/auth
ng g module modules/admin --routing

프로젝트 구조 개요

Angular는 명확한 폴더 구조를 강제합니다. src/app에 모든 기능 코드가 들어갑니다. main.ts가 루트 컴포넌트를 부트스트랩하고, angular.json은 빌드·테스트·서브 옵션을 설정합니다. environments 폴더에서 환경별로 API URL을 바꿔 쓸 수 있습니다.

angular
my-app/
├── src/
│   ├── app/                 # application code lives here
│   │   ├── app.component.ts
│   │   ├── app.component.html
│   │   └── app.config.ts    # standalone bootstrap config
│   ├── assets/              # static images, fonts
│   ├── environments/        # env-specific values
│   ├── index.html           # main HTML entry
│   ├── main.ts              # bootstrap entry point
│   └── styles.scss          # global styles
├── angular.json             # CLI workspace config
├── package.json
└── tsconfig.json

서빙과 빌드

ng serve는 기본적으로 4200 포트에서 HMR 방식의 리로드를 지원하는 개발 서버를 시작합니다. 프로덕션 빌드는 tree-shaking, 압축(minify), 캐싱용 파일명 해싱을 수행합니다. 비대해진 의존성을 찾으려면 --stats-json과 webpack-bundle-analyzer를 함께 사용하세요. ng test는 기본적으로 Karma를 실행합니다.

angular
# dev server with live reload
ng serve --port 4300 --open

# production build (outputs to dist/)
ng build --configuration production

# analyze bundle size
ng build --stats-json
npx webpack-bundle-analyzer dist/my-app/stats.json

# run unit tests (Karma + Jasmine)
ng test

# run end-to-end tests
ng e2e

코드 생성 (Schematics)

Schematics는 일관된 파일명과 보일러플레이트를 보장합니다. --standalone 플래그는 standalone 컴포넌트를 생성합니다(v17부터 권장). --route와 --module을 함께 쓰면 lazy-loaded 라우트가 자동으로 연결됩니다. --functional로 만든 가드는 클래스 대신 함수를 반환합니다.

angular
# generate a standalone component
ng g component user-profile --standalone

# generate a service with root provider
ng g service services/auth

# generate a guard (functional by default)
ng g guard guards/auth --functional

# generate a pipe, directive, or module
ng g pipe pipes/shorten
ng g directive directives/highlight
ng g module admin --routing --route admin --module app

# generate an interface or enum
ng g interface models/user
ng g enum models/role

설정 (angular.json)

angular.json은 워크스페이스 설정 파일입니다. 각 프로젝트는 build, serve, test, lint 타깃을 가집니다. budgets는 번들 크기가 임계값을 넘으면 경고나 오류를 냅니다. polyfills 배열에는 Angular에 필요한 zone.js가 포함됩니다. 하나의 워크스페이스에 여러 프로젝트(앱 + 라이브러리)를 함께 둘 수 있습니다.

angular
{
  "projects": {
    "my-app": {
      "architect": {
        "build": {
          "options": {
            "outputPath": "dist/my-app",
            "index": "src/index.html",
            "main": "src/main.ts",
            "polyfills": ["zone.js"],
            "tsConfig": "tsconfig.app.json",
            "assets": ["src/favicon.ico", "src/assets"],
            "styles": ["src/styles.scss"],
            "scripts": []
          },
          "configurations": {
            "production": {
              "budgets": [{ "type": "initial", "maximumWarning": "500kb" }]
            }
          }
        }
      }
    }
  }
}

환경 설정(Environments)

Angular는 빌드 시 설정(dev vs prod)에 따라 환경 파일을 교체합니다. 파일 교체는 angular.json의 fileReplacements에서 설정합니다. environment 객체를 원하는 곳에 주입하면 하드코딩 없이 환경별 값을 사용할 수 있습니다. 실제 시크릿을 소스 관리에 커밋하지 마세요.

angular
// src/environments/environment.ts
export const environment = {
  production: false,
  apiUrl: 'http://localhost:3000/api',
  apiKey: 'dev-key'
};

// src/environments/environment.prod.ts
export const environment = {
  production: true,
  apiUrl: 'https://api.example.com',
  apiKey: 'prod-key'
};

// usage in a service
import { environment } from '../environments/environment';

@Injectable({ providedIn: 'root' })
export class ApiService {
  private baseUrl = environment.apiUrl;
}
02

컴포넌트 기본

기본 컴포넌트

컴포넌트는 @Component 데코레이터가 붙은 TypeScript 클래스입니다. selector는 템플릿에서 사용할 커스텀 HTML 태그입니다. templateUrl/styleUrls는 외부 파일을 가리키고, 인라인으로 쓰려면 template/styles를 사용합니다. @Input은 부모가 바인딩할 수 있는 속성을 표시합니다. 컴포넌트는 하나의 책임에 집중하도록 유지하세요.

angular
// user-profile.component.ts
import { Component, Input } from '@angular/core';

@Component({
  selector: 'app-user-profile',
  templateUrl: './user-profile.component.html',
  styleUrls: ['./user-profile.component.scss'],
})
export class UserProfileComponent {
  @Input() name = 'Guest';
  @Input() age = 0;

  greet() {
    return `Hello, ${this.name}!`;
  }
}

인라인 템플릿 컴포넌트

인라인 템플릿은 작은 컴포넌트에 편리하고 파일을 추가로 만들 필요가 없습니다. 여러 줄 문자열에는 백틱을 사용하고, 내부의 백틱은 \`로 이스케이프합니다. styles는 CSS 문자열 배열을 받습니다. :host 셀렉터는 컴포넌트 자신의 엘리먼트를 대상으로 합니다. 템플릿이 10줄을 넘어가면 외부 파일로 분리하는 것이 좋습니다.

angular
@Component({
  selector: 'app-counter',
  template: `
    <button (click)="decrement()">-</button>
    <span>{{ count }}</span>
    <button (click)="increment()">+</button>
  `,
  styles: [`
    :host { display: flex; gap: 8px; align-items: center; }
    button { padding: 4px 12px; }
  `],
})
export class CounterComponent {
  count = 0;
  increment() { this.count++; }
  decrement() { this.count--; }
}

Standalone 컴포넌트 (v14+)

standalone 컴포넌트는 NgModule이 필요 없습니다. 자체 imports 배열에 의존성(CommonModule, FormsModule, 다른 컴포넌트)을 직접 선언합니다. 이것이 현재 권장되는 모던 방식입니다. 사용하는 것만 임포트하면 tree-shaking에 유리합니다. standalone 컴포넌트는 main.ts에서 직접 부트스트랩합니다.

angular
import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';

@Component({
  selector: 'app-search',
  standalone: true,
  imports: [CommonModule, FormsModule],
  template: `
    <input [(ngModel)]="query" placeholder="Search..." />
    <p>Searching for: {{ query }}</p>
  `,
})
export class SearchComponent {
  query = '';
}

Input과 Output

@Input은 부모가 프로퍼티 바인딩으로 데이터를 전달하게 해 줍니다. @Output은 부모가 이벤트 바인딩으로 구독하는 EventEmitter를 노출합니다. undefined 오류를 피하려면 항상 input에 기본값을 초기화하세요. v17 이상에서는 더 깔끔한 코드를 위해 새로운 input()/output() signals API를 사용하세요.

angular
@Component({
  selector: 'app-toggle',
  template: `
    <button (click)="toggle()">{{ label }}: {{ on ? 'On' : 'Off' }}</button>
  `,
})
export class ToggleComponent {
  @Input() label = 'Toggle';
  @Input() on = false;
  @Output() changed = new EventEmitter<boolean>();

  toggle() {
    this.on = !this.on;
    this.changed.emit(this.on);
  }
}

<!-- parent template -->
<app-toggle [label]="'Power'" [on]="isOn" (changed)="onToggle($event)" />

시그널 기반 Input (v17.1+)

input() 함수는 함수처럼 호출해서 읽는 시그널 기반 읽기 전용 input을 만듭니다. input.required<T>()로 필수 input을 지원하고, 변환(transform)을 적용할 수 있으며, computed()나 effect()와 자연스럽게 함께 동작합니다. output()은 @Output EventEmitter의 모던한 대체재입니다. 이것이 Angular 컴포넌트 API의 미래입니다.

angular
import { Component, input, output } from '@angular/core';

@Component({
  selector: 'app-card',
  template: `
    <div>{{ title() }} - {{ count() }}</div>
    <button (click)="clicked.emit()">Click</button>
  `,
})
export class CardComponent {
  // readonly signal inputs with defaults
  title = input<string>('Default');
  count = input<number>(0);

  // output() function replaces @Output
  clicked = output<void>();

  // computed derived from inputs
  // requires import { computed }
  // label = computed(() => this.title().toUpperCase());
}

뷰 캡슐화(View Encapsulation)

Emulated(기본값)는 고유한 속성을 추가해 실제 Shadow DOM 없이 컴포넌트 단위로 스타일을 한정합니다. None은 스타일을 전역으로 만듭니다(절제해서 사용). ShadowDom은 진짜 Shadow DOM으로 완전한 격리를 제공하지만 스타일 침투와 일부 서드파티 라이브러리에 영향을 줍니다. 특별한 이유가 없다면 Emulated를 유지하세요.

angular
@Component({
  selector: 'app-styles',
  template: `<p class="local">Emulated (default)</p>`,
  styles: [`p.local { color: red; }`],
  encapsulation: ViewEncapsulation.Emulated, // default
})
export class StylesComponent {}

// ViewEncapsulation.None    -> styles leak globally
// ViewEncapsulation.ShadowDom -> real Shadow DOM (strong isolation)
// ViewEncapsulation.Emulated -> scoped attributes (default, recommended)
03

템플릿 문법

텍스트 보간(Interpolation)

이중 중괄호 {{ }}는 표현식을 HTML 이스케이프된 텍스트로 렌더링합니다. 산술, 삼항 연산자, 메서드 호출, 프로퍼티 접근 등 대부분의 JS 표현식을 쓸 수 있습니다. new, typeof, 대입 연산자는 사용할 수 없습니다. 파이프(|)로 출력을 변환합니다. 보간은 변경 감지 사이클마다 다시 평가됩니다.

angular
<p>{{ title }}</p>                       <!-- renders the value -->
<p>{{ 1 + 2 }}</p>                        <!-- expressions allowed -->
<p>{{ user.name }}</p>                    <!-- property access -->
<p>{{ items.length }}</p>                 <!-- method/property -->
<p>{{ price | currency:'USD' }}</p>       <!-- pipe in interpolation -->
<p>{{ isReady ? 'Yes' : 'No' }}</p>       <!-- ternary -->

<!-- one-time interpolation updates when the source changes -->
<!-- new control flow @if, @for work without *ngIf/*ngFor directives -->

프로퍼티 바인딩과 어트리뷰트 바인딩

[prop]는 DOM 프로퍼티에 바인딩합니다(권장). [attr.name]은 DOM 프로퍼티가 없는 경우(colspan, SVG 속성 등)에 HTML 어트리뷰트에 바인딩합니다. [class.x]는 truthiness로 클래스 하나를 토글하고, [style.prop]은 .px나 % 같은 단위 접미사를 붙여 스타일을 설정합니다. 신뢰할 수 없는 콘텐츠를 innerHTML에 바인딩하지 마세요.

angular
<!-- property binding: [prop]="expression" -->
<img [src]="user.avatar" [alt]="user.name" />
<button [disabled]="isSaving">Save</button>
<my-comp [data]="items"></my-comp>

<!-- attribute binding (for attrs without DOM props) -->
<td [attr.colspan]="2">Merged cell</td>
<svg [attr.viewBox]="box"></svg>

<!-- class & style binding -->
<div [class.active]="isActive">Active?</div>
<div [class]="dynamicClassString">
<div [style.color]="colorVar">
<div [style.width.px]="size">Width</div>

이벤트 바인딩

(event)는 DOM 이벤트와 커스텀 EventEmitter 출력에 바인딩합니다. $event는 이벤트 페이로드입니다(네이티브 이벤트면 DOM Event, 커스텀이면 emit된 값). .enter, .esc, .prevent, .stop 같은 이벤트 수식어로 이벤트를 걸러내거나 변형할 수 있습니다. 괄호 안의 대상이 핸들러를 트리거합니다.

angular
<button (click)="save()">Save</button>
<input (input)="onInput($event)" (keyup)="onKey($event)" />
<div (mouseenter)="hover=true" (mouseleave)="hover=false">Hover</div>

<!-- $event is the DOM event object -->
<input (keyup.enter)="submit()" (keyup.esc)="cancel()" />

<!-- passive events (scroll, touchmove) -->
<div (scroll.passive)="onScroll($event)">...</div>

<!-- binding to custom component outputs -->
<app-child (changed)="onChanged($event)"></app-child>

템플릿 참조 변수

#var(ref-var)는 선언된 DOM 엘리먼트나 컴포넌트 인스턴스를 참조하며, 템플릿 어디서든 접근할 수 있습니다. 컴포넌트에서는 컴포넌트 인스턴스, 엘리먼트에서는 HTMLElement가 됩니다. @for 안에서는 $index, $first, $last, $even, $odd가 암묵적 컨텍스트 변수로 제공됩니다.

angular
<input #nameInput type="text" />
<button (click)="nameInput.focus()">Focus</button>
<p>You typed: {{ nameInput.value }}</p>

<!-- ref to a component instance -->
<app-form #f="appForm"></app-form>
<button [disabled]="!f.valid" (click)="f.submit()">Submit</button>

<!-- ref inside @for -->
<ul>
  @for (item of items; track item.id) {
    <li>{{ item.name }} (index: {{ $index }})</li>
  }
</ul>

양방향 바인딩 (바나나 상자)

[(ngModel)]은 FormsModule이 필요합니다. [(x)] 문법은 [x] + (xChange)로 풀어 해석되므로, 커스텀 양방향 바인딩에는 x라는 input과 xChange라는 output이 필요합니다. '바나나 상자'라는 니모닉을 기억하세요 — 괄호가 대괄호 안에 들어갑니다. v17.2 이상에서는 model() 시그널 함수가 이를 단순화합니다.

angular
<!-- [()] = "banana in a box" - property + event combined -->
<input [(ngModel)]="username" />

<!-- equivalent to -->
<input [ngModel]="username" (ngModelChange)="username = $event" />

<!-- two-way binding on custom components -->
<app-counter [(value)]="count"></app-counter>
<!-- requires: @Input() value; @Output() valueChange = new EventEmitter() -->

<!-- signals: model() for two-way (v17.2+) -->
// value = model<number>(0);

세이프 내비게이션과 널 아님 단언

?. 연산자는 nullable 체인을 안전하게 탐색하며, 예외를 던지는 대신 undefined를 반환합니다. 아직 로드되지 않은 비동기 데이터에 사용하세요. ! 연산자는 컴파일 타임 단언일 뿐 런타임 검사를 추가하지 않으므로 확실할 때만 사용합니다. null일 수 있는 배열에는 ?? []를 폴백으로 쓰세요.

angular
<!-- safe navigation: short-circuits to undefined if null -->
<p>{{ user?.profile?.bio }}</p>
<p>{{ user?.getName?.() }}</p>

<!-- non-null assertion: tells compiler it's not null -->
<p>{{ user!.name }}</p>

<!-- in property bindings -->
<img [src]="user?.avatar" />
<app-detail [data]="user!"></app-detail>

<!-- safe navigation in @for doesn't replace track -->
@for (item of items ?? []; track item.id) { ... }
04

디렉티브

@if / @else (새 제어 흐름)

새로운 @if/@else if/@else 블록 문법은 *ngIf를 대체합니다. CommonModule이나 NgIf를 임포트할 필요가 없고, 별표(*)도 없으며, ngIf의 ng-template 우회법과 달리 @else가 기본 동작합니다. 새 코드에서 권장되는 문법입니다. v17에 도입된 내장 제어 흐름의 일부로 v18에서 안정화되었습니다.

angular
@if (user) {
  <p>Hello, {{ user.name }}</p>
} @else if (loading) {
  <p>Loading...</p>
} @else {
  <p>No user found.</p>
}

<!-- no structural directive import needed, no * prefix -->
<!-- works in standalone templates automatically (v17+) -->

@for / @empty (새 제어 흐름)

@for는 *ngFor를 대체하며, 효율적인 DOM diffing을 위해 track 표현식이 필수입니다. @empty는 컬렉션이 비었을 때 폴백 콘텐츠를 렌더링합니다. 암묵적 컨텍스트 변수($index, $first, $last 등)는 항상 사용할 수 있습니다. 큰 목록의 성능을 위해서는 안정적인 고유 id로 track하는 것이 중요합니다.

angular
<ul>
  @for (item of items; track item.id) {
    <li>{{ item.name }} ({{ $index }})</li>
  } @empty {
    <li>No items yet.</li>
  }
</ul>

<!-- 'track' is REQUIRED for performance -->
<!-- implicit vars: $index, $first, $last, $even, $odd, $count -->

<!-- @for over a range -->
@for (i of [1,2,3,4,5]; track i) {
  <span>{{ i }}</span>
}

ngClass와 ngStyle

ngClass는 객체(truthy 키가 적용됨), 배열, 문자열을 받습니다. ngStyle은 camelCase나 kebab-case 키를 가진 객체와 선택적 단위 접미사를 받습니다. CommonModule이나 해당 디렉티브를 임포트해야 합니다. 클래스/스타일 하나만 다룰 때는 [class.x], [style.x]가 더 가볍고 임포트도 필요 없습니다.

angular
<div [ngClass]="{ active: isActive, disabled: !enabled }">Box</div>
<div [ngClass]="['card', 'shadow', themeClass]">Card</div>
<div [ngClass]="currentClass">String</div>

<div [ngStyle]="{ color: textColor, 'font-size.px': size }">Text</div>
<div [ngStyle]="styleObject">Styled</div>

<!-- import CommonModule (or NgClass/NgStyle) for these -->
<!-- prefer [class.x] and [style.x] for single value bindings -->

@switch (새 제어 흐름)

@switch는 *ngSwitch(및 ngSwitchCase/ngSwitchDefault 디렉티브)를 대체합니다. 래퍼 컨테이너도, 임포트도 필요 없어 더 깔끔합니다. 각 @case는 값이 @switch 표현식과 일치할 때만 렌더링되고, @default가 폴백입니다. v17 이상에서 사용 가능한 내장 제어 흐름입니다.

angular
@switch (status) {
  @case ('loading') {
    <spinner>Loading...</spinner>
  }
  @case ('error') {
    <p class="error">Something went wrong</p>
  }
  @case ('success') {
    <p>Done!</p>
  }
  @default {
    <p>Idle</p>
  }
}

커스텀 어트리뷰트 디렉티브

어트리뷰트 디렉티브는 DOM 엘리먼트의 모양이나 동작을 변경합니다. selector의 [대괄호]는 어트리뷰트 사용처와 매칭됩니다. ElementRef는 DOM에 직접 접근하게 하고, HostListener는 DOM 이벤트에 바인딩합니다. 타입 안전성을 위해 ElementRef<HTMLElement>를 주입하세요. 서버 사이드 렌더링 상황에서는 DOM 조작에 Renderer2를 선호합니다.

angular
import { Directive, ElementRef, Input, HostListener } from '@angular/core';

@Directive({
  selector: '[appHighlight]',
})
export class HighlightDirective {
  @Input('appHighlight') highlightColor = 'yellow';

  constructor(private el: ElementRef<HTMLElement>) {}

  @HostListener('mouseenter') onMouseEnter() {
    this.el.nativeElement.style.backgroundColor = this.highlightColor;
  }

  @HostListener('mouseleave') onMouseLeave() {
    this.el.nativeElement.style.backgroundColor = '';
  }
}

<!-- usage: <p appHighlight="lightblue">Hover me</p> -->

구조 디렉티브 내부 동작

구조 디렉티브는 TemplateRef(감싸진 템플릿)와 ViewContainerRef(삽입 위치)를 통해 DOM 노드를 추가/제거합니다. 별표(*)는 엘리먼트를 <ng-template>으로 감싸는 문법적 설탕입니다. 새로운 @if/@for/@switch 블록이 대부분의 커스텀 구조 디렉티브를 대체하지만, 고급 사례에서는 이 패턴이 여전히 유용합니다.

angular
import { Directive, TemplateRef, ViewContainerRef, Input } from '@angular/core';

@Directive({ selector: '[appUnless]' })
export class UnlessDirective {
  private hasView = false;

  @Input() set appUnless(condition: boolean) {
    if (!condition && !this.hasView) {
      this.vc.createEmbeddedView(this.tpl);
      this.hasView = true;
    } else if (condition && this.hasView) {
      this.vc.clear();
      this.hasView = false;
    }
  }

  constructor(private tpl: TemplateRef<unknown>, private vc: ViewContainerRef) {}
}

<!-- usage: <div *appUnless="hide">Shown when hide is false</div> -->
05

파이프(Pipes)

내장 파이프

파이프는 템플릿에서 표시되는 값을 변환합니다. 자주 쓰는 내장 파이프: date, number, currency, percent, uppercase, lowercase, titlecase, slice, json, async. 파이프는 기본적으로 pure이며 입력 참조가 바뀔 때만 다시 계산됩니다. 포맷 문자열은 Angular의 로케일 규칙을 따릅니다.

angular
<!-- date formatting -->
<p>{{ today | date }}</p>                          <!-- Sep 10, 2024 -->
<p>{{ today | date:'short' }}</p>
<p>{{ today | date:'yyyy-MM-dd HH:mm' }}</p>

<!-- number & currency -->
<p>{{ 3.14159 | number:'1.2-2' }}</p>               <!-- 3.14 -->
<p>{{ price | currency:'USD':'symbol':'1.2-2' }}</p>
<p>{{ ratio | percent }}</p>

<!-- text transforms -->
<p>{{ 'hello world' | uppercase }}</p>              <!-- HELLO WORLD -->
<p>{{ 'HELLO' | lowercase }}</p>
<p>{{ title | titlecase }}</p>
<p>{{ 'a/b/c' | slice:0:2 }}</p>

<!-- json (for debugging) -->
<pre>{{ obj | json }}</pre>

파이프 체이닝과 매개변수

파이프는 왼쪽에서 오른쪽으로 연결되며 각 파이프는 이전 출력을 받습니다. 매개변수는 콜론으로 구분되는 위치 인자입니다. 포맷팅, 필터링 같은 순수 변환에 사용해 템플릿을 선언적으로 유지하세요. 성능에 민감한 데이터에는 impure 파이프를 피하고 컴포넌트에서 계산하세요.

angular
<!-- chain: left to right, output of one feeds the next -->
<p>{{ '  hello  ' | trim | uppercase }}</p>         <!-- HELLO -->
<p>{{ birthday | date:'fullDate' | uppercase }}</p>
<p>{{ items | slice:0:3 | json }}</p>

<!-- parameters separated by colons -->
<p>{{ amount | number:'1.2-2':'en-US' }}</p>
<p>{{ meeting | date:'shortTime' }}</p>
<p>{{ list | slice:1:5 }}</p>

<!-- multiple parameters -->
<p>{{ value | myPipe:arg1:arg2:arg3 }}</p>

커스텀 파이프

커스텀 파이프는 PipeTransform.transform()을 구현합니다. @Pipe의 name이 템플릿에서 사용됩니다. standalone 파이프(v15+)는 컴포넌트의 imports 배열에 등록하거나 NgModule에 선언합니다. pure 파이프(기본값)는 입력 참조가 바뀔 때만 다시 실행되므로, 업데이트를 트리거하려면 새 참조를 전달해야 합니다.

angular
import { Pipe, PipeTransform } from '@angular/core';

@Pipe({ name: 'truncate' })
export class TruncatePipe implements PipeTransform {
  transform(value: string, limit = 20, ellipsis = '...'): string {
    if (!value) return '';
    return value.length > limit
      ? value.slice(0, limit) + ellipsis
      : value;
  }
}

// register in a standalone component imports:
// imports: [TruncatePipe]

<!-- usage -->
<p>{{ longText | truncate:50 }}</p>
<p>{{ longText | truncate:10:'>>' }}</p>

Async 파이프

async 파이프는 Observable이나 Promise를 구독해 값을 렌더링하고, destroy 시 자동으로 구독을 해제합니다 — 수동 subscribe/unsubscribe가 필요 없습니다. *ngIf as나 @for와 조합하면 로딩 중 null을 깔끔하게 처리합니다. 새 값이 도착하면 컴포넌트를 검사 대상으로 표시해 OnPush와도 통합됩니다.

angular
@Component({
  selector: 'app-user',
  template: `
    <div *ngIf="user$ | async as user">
      {{ user.name }}
    </div>
    <ul>
      @for (item of items$ | async; track item.id) {
        <li>{{ item.name }}</li>
      }
    </ul>
  `,
  imports: [AsyncPipe, NgIf],
})
export class UserComponent {
  user$ = this.http.get<User>('/api/user');
  items$ = this.http.get<Item[]>('/api/items');

  constructor(private http: HttpClient) {}
}

Pure vs Impure 파이프

pure 파이프는 입력 참조가 바뀔 때까지 결과를 캐싱하므로 배열이나 객체를 변형(mutate)해도 트리거되지 않습니다. impure 파이프(pure: false)는 모든 변경 감지마다 다시 실행됩니다 — 변형된 배열 필터링에 편리하지만 비용이 큽니다. 데이터를 불변으로 유지(변형 대신 배열 교체)하고 pure 파이프를 사용하는 것이 성능상 좋습니다.

angular
// PURE (default): re-runs only when input reference changes
@Pipe({ name: 'filter' })
export class FilterPipe implements PipeTransform {
  transform(items: Item[], term: string): Item[] {
    return items.filter(i => i.name.includes(term));
  }
}
// Issue: mutating items.push() won't trigger re-evaluation.

// IMPURE: re-runs on every change detection cycle
@Pipe({ name: 'filter', pure: false })
export class ImpureFilterPipe implements PipeTransform { ... }
// ⚠️ Expensive! Use sparingly — affects performance.

i18n과 로케일 파이프

date, number, currency 같은 파이프는 LOCALE_ID를 존중합니다. 부트스트랩 전에 registerLocaleData로 로케일 데이터를 등록하세요. currency/decimal 포맷은 활성 로케일을 따릅니다. 다국어 앱에서는 사용자별로 LOCALE_ID를 제공하거나 i18n 도구로 템플릿 번역을 처리합니다. 로케일 데이터가 없으면 en-US로 폴백합니다.

angular
// register locale data in app.config.ts
import { registerLocaleData } from '@angular/common';
import localeFr from '@angular/common/locales/fr';
registerLocaleData(localeFr);

// provide a default locale
providers: [{ provide: LOCALE_ID, useValue: 'fr-FR' }]

// usage - now locale-aware
<p>{{ price | currency:'EUR' }}</p>          <!-- 1 234,56 € -->
<p>{{ today | date:'fullDate' }}</p>          <!-- lundi 10 septembre 2024 -->
<p>{{ number | number:'1.2-2' }}</p>          <!-- 1 234,56 -->
<p>{{ amount | currency:'JPY' }}</p>          <!-- ¥1,235 -->
06

서비스와 의존성 주입

기본 서비스

providedIn: 'root'는 모듈 등록 없이 앱 전역에서 사용 가능한 싱글턴을 만듭니다. 서비스는 tree-shakeable해서 사용하지 않으면 제거됩니다. 생성자 주입 대신 inject() 함수(v14+)를 쓰면 코드가 더 깔끔하고 테스트도 쉬워집니다. 서비스는 공유 상태와 비즈니스 로직을 담당하고, 컴포넌트는 프레젠테이션에 집중합니다.

angular
import { Injectable } from '@angular/core';

@Injectable({ providedIn: 'root' })
export class UserService {
  private users = ['Alice', 'Bob'];

  getUsers() { return this.users; }
  addUser(name: string) { this.users.push(name); }
}

// usage in a component
export class UserListComponent {
  // Angular injects the singleton instance
  constructor(private users: UserService) {}

  get users() { return this.usersService.getUsers(); }
  private usersService = inject(UserService);
}

inject() 함수

inject()는 생성자 주입의 모던한 대안입니다. 필드 이니셜라이저에서 동작해 코드 가독성이 좋아지고 TypeScript 추론도 개선됩니다. 생성 중에 실행되어야 합니다(이후 비동기 콜백에서는 안 됨). 일관되게 사용하세요 — 생성자 파라미터와 inject()를 섞어 써도 되지만 inject()가 더 깔끔합니다.

angular
import { Injectable, inject } from '@angular/core';

@Injectable({ providedIn: 'root' })
export class AuthService {
  private http = inject(HttpClient);
  private router = inject(Router);

  login(creds: Credentials) {
    return this.http.post('/api/login', creds);
  }
}

// in a component
export class DashboardComponent {
  private auth = inject(AuthService);
  user = this.auth.currentUser;   // works in field initializers
}

프로바이더 설정

프로바이더는 어떤 수준에서도(root, module, component) 설정할 수 있습니다. useClass는 구현체를 교체합니다(모킹에 유용). useValue는 상수를 제공합니다. useExisting은 한 서비스를 다른 서비스로 별칭 지정합니다. useFactory는 인스턴스를 동적으로 생성합니다. InjectionToken은 문자열이나 설정 객체 같은 비클래스 값에 사용합니다.

angular
@Component({
  // ... provide at component level for instance-per-component
  providers: [
    UserService,                              // shorthand
    { provide: Logger, useClass: ConsoleLogger },
    { provide: API_URL, useValue: 'https://api.example.com' },
    { provide: Storage, useExisting: LocalStorageService },
    {
      provide: Config,
      useFactory: () => new Config(env.production)
    },
  ],
})
export class AdminComponent {}

// InjectionToken for non-class values
export const API_URL = new InjectionToken<string>('API_URL');

계층적 인젝터

Angular의 DI 트리는 컴포넌트 트리를 반영합니다. providedIn: 'root'는 앱 전역에 하나의 인스턴스입니다. 컴포넌트 수준 프로바이더는 자식 인젝터를 만들어 각 인스턴스가 자신만의 것을 갖게 합니다. 에디터 같은 상태를 가진 컴포넌트에 유용합니다. 'any'는 lazy 모듈 단위로 스코프를 한정하고, 'platform'은 드물며 멀티 앱 구성에 사용됩니다.

angular
// root injector (singleton app-wide)
@Injectable({ providedIn: 'root' })
export class AuthService {}

// component-level provider: new instance for this component and children
@Component({
  providers: [UserService],   // each AdminComponent gets its own UserService
})
export class AdminComponent {}

// 'any' creates a lazy singleton per lazy module
@Injectable({ providedIn: 'any' })
export class SharedService {}

// 'platform' shared across all Angular apps on the page
@Injectable({ providedIn: 'platform' })
export class GlobalConfig {}

멀티 프로바이더와 토큰

multi: true는 하나의 토큰 아래 여러 프로바이더를 등록하며, 배열로 주입됩니다. 플러그인 시스템, 인터셉터, 밸리데이터 등 확장 가능한 컬렉션에 유용합니다. 주입 순서는 등록 순서를 따릅니다. InjectionToken과 조합하면 배열에 타입을 부여할 수 있습니다.

angular
// define a token for a list of plugins
export const PLUGIN = new InjectionToken<Plugin>('PLUGIN');

// provide multiple plugins
@Component({
  providers: [
    { provide: PLUGIN, useClass: AuthPlugin, multi: true },
    { provide: PLUGIN, useClass: AnalyticsPlugin, multi: true },
  ],
})
export class AppComponent {}

// inject all of them as an array
export class PluginManager {
  plugins = inject(PLUGIN);   // Plugin[]
}

옵셔널 및 기본 프로바이더

@Optional() 또는 inject(token, { optional: true })는 프로바이더가 없으면 예외 대신 null을 반환합니다. 필수가 아닌 의존성에 사용하세요. 다른 수식어: @SkipSelf()(현재 인젝터를 건너뜀), @Self()(현재만), @Host()(호스트 컴포넌트까지). inject()도 옵션 객체에 플래그를 받아 동일하게 동작합니다.

angular
import { Injectable, inject, Optional, Inject } from '@angular/core';

@Injectable({ providedIn: 'root' })
export class Logger {
  constructor(@Optional() @Inject(CONFIG) private cfg?: Config) {
    // cfg is null if no provider exists — handle gracefully
  }
}

// or with inject()
export class Service {
  cfg = inject(CONFIG, { optional: true });   // Config | null
  baseUrl = inject(API_URL, { optional: true }) ?? '/api';
}

// skipSelf: look in parent injectors only
// self: only this component's injector
// host: limit to host component
07

라우팅

라우트 설정

라우트는 URL 경로를 컴포넌트에 매핑합니다. loadComponent/loadChildren은 lazy loading을 활성화합니다(초기 번들 축소). :id는 라우트 파라미터입니다. 와일드카드 '**'는 매칭되지 않는 URL을 잡으며 마지막에 배치합니다. provideRouter는 standalone 앱에서 라우터를 설정합니다. 브라우저 탭 이름용 title을 지정하세요 — 문자열이나 ResolveFn이 될 수 있습니다.

angular
// app.routes.ts (standalone)
import { Routes } from '@angular/router';

export const routes: Routes = [
  { path: '', component: HomeComponent, title: 'Home' },
  { path: 'about', loadComponent: () => import('./about/about.component')
      .then(m => m.AboutComponent) },
  { path: 'users/:id', component: UserDetailComponent },
  { path: 'admin', loadChildren: () => import('./admin/admin.routes')
      .then(m => m.ADMIN_ROUTES) },
  { path: '**', component: NotFoundComponent },   // wildcard
];

// app.config.ts
export const appConfig: ApplicationConfig = {
  providers: [provideRouter(routes)]
};

Router Outlet과 링크

router-outlet은 라우팅된 컴포넌트가 렌더링될 위치를 표시합니다. routerLink는 내비게이션 링크를 만듭니다(파라미터는 배열 형태 사용). routerLinkActive는 라우트가 일치할 때 클래스를 적용합니다. 프로그래밍 방식 내비게이션은 router.navigate()나 routerLink를 사용합니다. 명명된 outlet으로 보조 라우트(예: 메인 뷰 옆의 모달)를 만들 수 있습니다.

angular
<!-- app.component.html -->
<nav>
  <a routerLink="/" routerLinkActive="active">Home</a>
  <a routerLink="/about" routerLinkActive="active">About</a>
  <a [routerLink]="['/users', userId]">My Profile</a>
</nav>

<router-outlet></router-outlet>

<!-- named outlet (secondary route) -->
<router-outlet name="popup"></router-outlet>

<!-- navigate programmatically -->
<button (click)="go()">Go</button>
// constructor(private router: Router) {}
// go() { this.router.navigate(['/users', 42]); }

라우트 파라미터와 쿼리 파라미터

컴포넌트가 내비게이션마다 파괴 후 재생성된다면 일회성 읽기에 snapshot을 사용하세요. 같은 컴포넌트 인스턴스가 다른 파라미터를 처리한다면(/users/1에서 /users/2로 이동 등) observable인 paramMap/queryParamMap을 사용하세요. 누수를 막으려면 항상 구독을 해제하거나 async 파이프를 쓰세요.

angular
// reading route params
export class UserDetailComponent {
  constructor(private route: ActivatedRoute) {
    // snapshot: one-time read (good for static links)
    const id = this.route.snapshot.paramMap.get('id');

    // observable: reacts to param changes (same component reused)
    this.route.paramMap.subscribe(params => {
      console.log(params.get('id'));
    });
  }
}

// query params: /search?q=angular&page=2
this.route.queryParamMap.subscribe(qp => {
  this.q = qp.get('q');
});

<!-- link with query params -->
<a [routerLink]="['/search']" [queryParams]="{ q: 'angular', page: 2 }">

자식 라우트와 중첩 라우트

자식 라우트는 부모 컴포넌트 안의 중첩 router-outlet에 렌더링됩니다. redirectTo에 pathMatch: 'full'을 조합하면 빈 자식 경로를 리다이렉트합니다. 이 패턴은 마스터-디테일 레이아웃(부모 틀, 자식 콘텐츠)을 만듭니다. 중첩 단계마다 부모 템플릿에 자체 router-outlet이 필요합니다.

angular
export const routes: Routes = [
  {
    path: 'admin',
    component: AdminLayoutComponent,
    children: [
      { path: '', redirectTo: 'dashboard', pathMatch: 'full' },
      { path: 'dashboard', component: DashboardComponent },
      { path: 'users', component: AdminUsersComponent },
      { path: 'settings', component: SettingsComponent },
    ],
  },
];

<!-- AdminLayoutComponent template -->
<h2>Admin Panel</h2>
<nav>...</nav>
<router-outlet></router-outlet>   <!-- child routes render here -->

Lazy Loading

lazy loading은 앱을 필요할 때 로드되는 청크로 분할해 초기 번들을 줄입니다. loadChildren은 라우트 파일(Routes의 default export)을 로드하고, loadComponent는 standalone 컴포넌트 하나를 로드합니다. 번들러가 올바르게 분할하려면 dynamic import()의 문자열이 정적 경로여야 합니다. 내비게이션 뒤에 숨은 기능 영역에 사용하세요.

angular
// main routes - load feature modules on demand
export const routes: Routes = [
  { path: '', component: HomeComponent },
  {
    path: 'admin',
    loadChildren: () => import('./admin/admin.routes').then(m => m.ADMIN_ROUTES),
  },
  {
    path: 'reports',
    loadComponent: () => import('./reports/reports.component')
      .then(m => m.ReportsComponent),
  },
];

// admin.routes.ts
export const ADMIN_ROUTES: Routes = [
  { path: '', component: AdminComponent },
  { path: 'users', component: AdminUsersComponent },
];

라우터 이벤트와 내비게이션

라우터 이벤트(NavigationStart, NavigationEnd, GuardsCheckStart 등)로 내비게이션 생명주기를 추적할 수 있습니다. 항상 특정 이벤트로 필터링하고 구독을 해제하세요. router.navigate는 extras로 queryParams, fragment, state(URL에 없는 임시 데이터), replaceUrl을 받습니다. state는 router.getCurrentNavigation().extras.state로 읽을 수 있습니다.

angular
// subscribe to router events
export class AppComponent implements OnDestroy {
  private sub = this.router.events.pipe(
    filter((e): e is NavigationEnd => e instanceof NavigationEnd)
  ).subscribe(e => {
    console.log('Navigated to:', e.url);
    this.analytics.track(e.url);
  });

  constructor(private router: Router) {}
  ngOnDestroy() { this.sub.unsubscribe(); }
}

// navigation with extras
this.router.navigate(['/users'], {
  queryParams: { sort: 'name' },
  fragment: 'top',
  state: { from: 'login' },   // passed to next route, not in URL
});
08

폼(Forms)

템플릿 기반 폼

템플릿 기반 폼은 ngModel과 템플릿 참조를 사용하며 FormsModule이 필요합니다. 폼의 상태(유효성, touched, dirty)는 ngForm과 ngModel 디렉티브로 추적됩니다. 단순한 폼에 적합합니다. 유효성 검사는 템플릿에서 선언합니다(required, minlength, pattern). #e='ngModel' 같은 템플릿 참조로 컨트롤 상태에 접근합니다.

angular
import { FormsModule } from '@angular/forms';

@Component({
  selector: 'app-login',
  standalone: true,
  imports: [FormsModule],
  template: `
    <form #f="ngForm" (ngSubmit)="save(f.value)">
      <input name="email" [(ngModel)]="email" required email #e="ngModel" />
      <span *ngIf="e.invalid && e.touched">Email required</span>

      <input name="pwd" type="password" [(ngModel)]="pwd" required minlength="6" />
      <button [disabled]="f.invalid">Submit</button>
    </form>
  `,
})
export class LoginComponent {
  email = '';
  pwd = '';
  save(v: any) { console.log(v); }
}

리액티브 폼 설정

리액티브 폼은 컴포넌트 클래스에서 FormControl/FormGroup 인스턴스로 모델을 정의하며 ReactiveFormsModule이 필요합니다. formControlName으로 input을 컨트롤에 바인딩합니다. 폼 모델은 observable이라 DOM 없이 테스트할 수 있습니다. nonNullable: true는 input이 비워졌을 때 null이 되지 않게 합니다. 복잡한 폼에 선호됩니다.

angular
import { ReactiveFormsModule, FormControl, FormGroup } from '@angular/forms';

@Component({
  selector: 'app-profile',
  imports: [ReactiveFormsModule],
  template: `
    <form [formGroup]="form" (ngSubmit)="save()">
      <input formControlName="name" />
      <input formControlName="email" />
      <button [disabled]="form.invalid">Save</button>
    </form>
    <p>Valid: {{ form.valid }}</p>
  `,
})
export class ProfileComponent {
  form = new FormGroup({
    name: new FormControl('', { nonNullable: true }),
    email: new FormControl('', { nonNullable: true }),
  });
  save() { console.log(this.form.value); }
}

FormBuilder와 타입 폼

FormBuilder는 보일러플레이트를 줄여 줍니다. fb.group()은 기본값에서 타입을 추론합니다. 중첩 그룹은 중첩 데이터를 모델링하고, FormArray는 동적 컨트롤 목록을 관리합니다. nonNullable을 쓰면 컨트롤이 null 대신 선언된 타입을 유지합니다. get()이나 controls로 타입 안전하게 접근하세요. 타입 폼(v14+)은 자동완성과 value 타입 검사를 제공합니다.

angular
import { FormBuilder, FormGroup } from '@angular/forms';

export class CheckoutComponent {
  private fb = inject(FormBuilder);

  // typed form (v14+ nonNullable)
  form = this.fb.group({
    name: ['', { nonNullable: true }],
    address: this.fb.group({
      street: [''],
      city: [''],
      zip: [''],
    }),
    items: this.fb.array<CartItem>([]),
  });

  // type-safe access
  get items() { return this.form.controls.items; }
  addItem(item: CartItem) { this.items.push(this.fb.control(item)); }
}

폼 유효성 검사

Validators.required, .minLength, .maxLength, .pattern, .email, .min, .max가 내장되어 있으며 배열로 여러 개를 적용합니다. 필드 간 검증은 FormGroup에 배치하며, 밸리데이터 함수가 그룹 전체를 받습니다. 첫 렌더링에서 사용자를 다그치지 않도록 오류 표시 전에 control.touched/dirty를 확인하세요. .hasError('key')로 특정 오류를 검사합니다.

angular
import { Validators } from '@angular/forms';

// built-in validators
const email = new FormControl('', [
  Validators.required,
  Validators.email,
  Validators.maxLength(100),
]);

const password = new FormControl('', [
  Validators.required,
  Validators.minLength(8),
  Validators.pattern(/[A-Z]/),
]);

// cross-field validation at group level
const form = this.fb.group({
  pwd: ['', Validators.required],
  confirm: ['', Validators.required],
}, { validators: matchPassword });   // custom group validator

// reading state in template
<!-- <span *ngIf="email.touched && email.hasError('required')">Required</span> -->

커스텀 밸리데이터

커스텀 밸리데이터는 ValidationErrors(맵)를 반환하거나 유효하면 null을 반환하는 함수입니다. 비동기 밸리데이터는 Observable이나 Promise를 반환하며, 아이디 중복 확인 같은 서버 측 검사에 사용합니다. 키 입력마다 서버를 두드리지 않도록 비동기 밸리데이터에는 반드시 디바운스(timer/switchMap)를 적용하세요.

angular
import { AbstractControl, ValidationErrors, ValidatorFn } from '@angular/forms';

// function validator
export const matchPassword: ValidatorFn = (group: AbstractControl): ValidationErrors | null => {
  const pwd = group.get('pwd')?.value;
  const confirm = group.get('confirm')?.value;
  return pwd === confirm ? null : { mismatch: true };
};

// async validator (returns Observable/Promise)
export function uniqueUsername(http: HttpClient): AsyncValidatorFn {
  return (control: AbstractControl) => {
    return timer(500).pipe(
      switchMap(() => http.get(`/api/check/${control.value}`)),
      map(exists => exists ? { taken: true } : null),
    );
  };
}

폼 값 변경과 상태

valueChanges와 statusChanges는 입력마다 값을 방출하는 Observable입니다. debounceTime은 빠른 타이핑에 과도한 작업을 막아 줍니다. 파괴 시 구독 해제는 Subject와 takeUntil 조합이 관용적입니다. patchValue는 일부 폼 값을 업데이트하고, setValue는 모든 필드를 요구합니다. valueChanges를 트리거하지 않고 조용히 업데이트하려면 { emitEvent: false }를 사용하세요.

angular
export class FilterComponent implements OnDestroy {
  private destroy = new Subject<void>();
  form = this.fb.group({ q: [''], category: ['all'] });

  ngOnInit() {
    // react to entire form changes (debounced)
    this.form.valueChanges.pipe(
      debounceTime(300),
      takeUntil(this.destroy),
    ).subscribe(v => this.search(v));

    // react to a single control
    this.form.controls.q.valueChanges.subscribe(q => {
      console.log('q changed:', q);
    });
  }

  ngOnDestroy() { this.destroy.next(); }
}
09

HttpClient

설정과 기본 GET

provideHttpClient()는 클라이언트를 앱 전역에 등록합니다. HttpClient 메서드는 cold Observable을 반환하므로 구독해야 실행됩니다(템플릿에서는 async 파이프, 서비스에서는 subscribe 사용). 응답은 제네릭으로 타입을 지정합니다. 오류는 중앙에서 또는 호출별로 반드시 처리하세요. withFetch()(v18)는 모던한 fetch 기반 백엔드로 전환합니다.

angular
// app.config.ts
import { provideHttpClient } from '@angular/common/http';

export const appConfig: ApplicationConfig = {
  providers: [provideHttpClient()],
};

// usage in a service
@Injectable({ providedIn: 'root' })
export class PostService {
  private http = inject(HttpClient);
  private api = 'https://jsonplaceholder.typicode.com/posts';

  getPosts() {
    return this.http.get<Post[]>(this.api);
  }
}

// in a component (use async pipe to auto-unsubscribe)
export class PostListComponent {
  posts$ = this.posts.getPosts();
  constructor(private posts: PostService) {}
}

POST / PUT / DELETE

post/put/patch는 응답을 한 번 방출하고 완료되는 Observable을 반환합니다. 본문은 두 번째 인자로 전달하고, 제네릭 타입으로 응답을 좁힙니다. URL은 파라미터가 포함된 템플릿 리터럴이 될 수 있습니다. 반드시 subscribe하세요 — Observable은 cold라 그렇지 않으면 실행되지 않습니다. 일회성 읽기에는 toPromise()(지원 중단)나 firstValueFrom()을 고려하세요.

angular
export class PostService {
  private http = inject(HttpClient);

  create(post: Omit<Post, 'id'>) {
    return this.http.post<Post>('/api/posts', post);
  }

  update(id: number, patch: Partial<Post>) {
    return this.http.put<Post>(`/api/posts/${id}`, patch);
  }

  remove(id: number) {
    return this.http.delete<void>(`/api/posts/${id}`);
  }
}

// all return Observables — subscribe or use async pipe
// HTTP methods return a single value then complete

쿼리 파라미터와 헤더

params는 객체, HttpParams, 배열을 받으며 Angular가 쿼리 문자열로 인코딩합니다. headers는 요청 헤더를 설정합니다. observe: 'response'는 본문만이 아니라 전체 HttpResponse(상태, 헤더, 본문)를 반환합니다. observe: 'events'와 reportProgress를 함께 쓰면 파일 업로드/다운로드의 진행 이벤트를 스트리밍합니다.

angular
export class SearchService {
  private http = inject(HttpClient);

  search(term: string, page = 1) {
    return this.http.get<Result[]>('/api/search', {
      params: { q: term, page, sort: 'desc' },
      headers: { 'X-Api-Key': 'secret' },
      observe: 'response',   // get full HttpResponse
      responseType: 'json',
    });
  }

  // observe: 'events' streams upload/download progress
  upload(file: File) {
    return this.http.post('/api/upload', file, {
      reportProgress: true,
      observe: 'events',
    });
  }
}

인터셉터

함수형 인터셉터(v15+)는 withInterceptors()로 체이닝되는 일반 함수입니다. 모든 요청에 순서대로 실행되며, 인증 토큰, 로깅, 재시도, 캐싱에 적합합니다. clone()은 수정된 요청을 만듭니다(요청은 불변). next(req) 함수가 응답 스트림을 반환하므로 retry, catchError 같은 pipe 연산자를 여기에 적용합니다.

angular
// functional interceptor (v15+)
export const authInterceptor: HttpInterceptorFn = (req, next) => {
  const token = localStorage.getItem('token');
  const authReq = token
    ? req.clone({ setHeaders: { Authorization: `Bearer ${token}` } })
    : req;
  return next(authReq);
};

// register in app.config.ts
providers: [provideHttpClient(withInterceptors([authInterceptor]))]

// error/logging interceptor
export const loggingInterceptor: HttpInterceptorFn = (req, next) => {
  console.log('Request:', req.url);
  return next(req).pipe(tap({
    error: e => console.error('Failed:', req.url, e),
  }));
};

오류 처리

HTTP 복원력에는 RxJS 연산자를 사용하세요: retry는 오류 시 재구독, timeout은 느린 요청을 중단, catchError는 오류를 폴백 값으로 매핑하거나 재던집니다. 소비자 측에서도 오류를 반드시 처리하세요 — 처리되지 않은 Observable 오류는 스트림을 멈춥니다. 전체 생명주기를 다루려면 next/error/complete 콜백으로 구독하세요.

angular
export class PostService {
  getPost(id: number) {
    return this.http.get<Post>(`/api/posts/${id}`).pipe(
      retry(2),                              // retry on failure
      timeout(5000),                         // abort after 5s
      catchError(err => {
        if (err.status === 404) return of(null);   // graceful fallback
        return throwError(() => new Error('Network error'));
      }),
    );
  }
}

// component-side
this.posts.getPost(1).subscribe({
  next: p => this.post = p,
  error: e => this.error = e.message,
  complete: () => this.loading = false,
});

타입 응답과 withFetch

제네릭은 응답 본문에 타입을 지정할 뿐 런타임에 검증하지 않습니다 — 안전을 위해 zod 같은 런타임 밸리데이터를 사용하세요. observe: 'response'는 status, headers, body를 노출합니다. withFetch()(v18)는 XHR 대신 Fetch API를 사용해 스트리밍과 더 나은 서버 사이드 렌더링을 지원합니다. withXsrfConfiguration은 자동 CSRF 토큰 처리를 추가합니다.

angular
// typed generic — response is typed, runtime NOT validated
this.http.get<User[]>('/api/users');

// full HttpResponse observation
this.http.get<User>('/api/users/1', { observe: 'response' })
  .subscribe(res => {
    console.log(res.status);   // 200
    console.log(res.headers.get('X-Total-Count'));
    console.log(res.body);     // User
  });

// opt into fetch() backend (v18+, recommended)
// provideHttpClient(withFetch())

// with XSRF protection enabled
// provideHttpClient(withXsrfConfiguration({ cookieName: 'XSRF-TOKEN' }))
10

Observable과 RxJS

기본 Observable

Observable은 지연(lazy) 동작합니다 — 구독해야 생산자가 실행됩니다. 값을 0개 이상 방출한 뒤 complete하거나 error합니다. subscribe 콜백은 next, error, complete를 받습니다. 오래 살아있는 구독은 반드시 해제하세요(또는 async 파이프 / takeUntilDestroyed 사용). of()는 값을 동기적으로 방출하고, from()은 배열이나 프로미스를 평탄화합니다.

angular
import { Observable } from 'rxjs';

const obs = new Observable<number>(subscriber => {
  subscriber.next(1);
  subscriber.next(2);
  setTimeout(() => {
    subscriber.next(3);
    subscriber.complete();
  }, 1000);
});

const sub = obs.subscribe({
  next: v => console.log(v),
  error: e => console.error(e),
  complete: () => console.log('done'),
});

// cleanup
sub.unsubscribe();

// use of(...) for synchronous values
of(1, 2, 3).subscribe(v => console.log(v));
// from(iterable) for arrays/async iterables
from([1, 2, 3]).subscribe(console.log);

자주 쓰는 연산자

연산자는 스트림을 변환합니다. map/filter는 배열 메서드처럼 동작합니다. debounceTime은 조용한 기간을 기다립니다(검색 입력에 유용). distinctUntilChanged는 연속된 중복 값을 건너뜁니다. switchMap은 새 값이 오면 이전 내부 Observable을 취소합니다 — 검색어 입력에 완벽합니다. pipe 연산자는 왼쪽에서 오른쪽으로 실행됩니다.

angular
import { of, from, interval } from 'rxjs';
import { map, filter, switchMap, debounceTime, distinctUntilChanged } from 'rxjs/operators';

of(1, 2, 3, 4).pipe(
  map(x => x * 10),                          // 10, 20, 30, 40
  filter(x => x > 15),                       // 20, 30, 40
).subscribe(console.log);

// search input with debounce
input$.pipe(
  debounceTime(300),
  distinctUntilChanged(),
  switchMap(term => http.get(`/api/search?q=${term}`)),
).subscribe(results => this.results = results);

스트림 조합

combineLatest는 모든 소스가 최소 한 번 방출한 후 소스 중 하나가 방출할 때마다 방출됩니다 — 파생 뷰 상태에 유용합니다. forkJoin은 모든 소스가 완료되길 기다렸다가 각각의 마지막 값을 반환합니다 — 병렬 HTTP 요청에 사용하세요. merge는 방출을 섞고, zip은 인덱스로 짝지으며, race는 먼저 방출한 Observable만 택하고 나머지는 무시합니다.

angular
import { combineLatest, forkJoin, merge, race, zip } from 'rxjs';

// combineLatest: emits when ANY source emits, after all have emitted
combineLatest([user$, settings$]).subscribe(([u, s]) => ...);

// forkJoin: waits for all to complete, emits last values (like Promise.all)
forkJoin({ user: user$, posts: posts$ }).subscribe(r => ...);

// merge: emits values from all sources as they come
merge(clicks$, keys$).subscribe(e => ...);

// zip: pairs emissions by index
zip(range(1, 3), ['a', 'b', 'c']).subscribe(([n, letter]) => ...);

// race: takes the first to emit, ignores the rest
race(primary$, fallback$).subscribe(v => ...);

Subject (멀티캐스팅)

Subject는 Observable이자 Observer입니다 — .next()로 값을 밀어 넣습니다. Subject: 초기값이 없고 늦게 구독하면 이전 방출을 놓칩니다. BehaviorSubject: 초기값이 필요하고 새 구독자에게 즉시 현재 값을 줍니다(상태에 사용). ReplaySubject: 최근 N개 값을 버퍼링해 새 구독자에게 제공합니다(이벤트 리플레이에 사용).

angular
import { Subject, BehaviorSubject, ReplaySubject } from 'rxjs';

// Subject: emits to current subscribers only
const click$ = new Subject<MouseEvent>();
click$.subscribe(x => console.log('A:', x));
click$.next({} as MouseEvent);   // A: logs it

// BehaviorSubject: keeps last value, new subs get it immediately
const count$ = new BehaviorSubject(0);
count$.subscribe(v => console.log(v));   // logs 0 immediately
count$.next(1);                          // logs 1 to subscribers

// ReplaySubject: replays last N values to new subscribers
const recent$ = new ReplaySubject<string>(2);
recent$.next('a'); recent$.next('b'); recent$.next('c');
recent$.subscribe(v => console.log(v));  // logs 'b', then 'c'

takeUntil과 정리

takeUntil(unsubscribe$)은 notifier가 방출하면 구독을 자동 완료합니다 — 컴포넌트 누수 방지의 표준 패턴입니다. takeUntilDestroyed()(v16+)는 Angular의 DestroyRef를 사용해 OnDestroy 보일러플레이트 없이 자동 구독 해제합니다. 주입 컨텍스트(생성자 또는 필드 이니셜라이저)에서 호출하거나 DestroyRef를 명시적으로 전달해야 합니다.

angular
import { Subject, takeUntil, takeUntilDestroyed } from 'rxjs';

export class DemoComponent implements OnDestroy {
  private destroy$ = new Subject<void>();

  ngOnInit() {
    this.svc.stream$.pipe(
      takeUntil(this.destroy$),
    ).subscribe(data => this.data = data);
  }

  ngOnDestroy() { this.destroy$.next(); this.destroy$.complete(); }
}

// v16+: takeUntilDestroyed (uses DestroyRef, no boilerplate)
export class DemoComponent {
  data: any;
  constructor() {
    inject(SomeService).stream$.pipe(
      takeUntilDestroyed(),
    ).subscribe(d => this.data = d);
  }
}

switchMap vs mergeMap vs concatMap

이 평탄화 연산자들은 겹치는 내부 Observable을 처리하는 방식이 다릅니다. switchMap은 취소합니다(입력 검색). mergeMap은 병렬 처리합니다(많이 로드). concatMap은 대기열에 넣습니다(순서 유지). exhaustMap은 무시합니다(중복 제출 방지). 잘못 고르면 경쟁 상태가 생기므로, 유스케이스의 취소 의미에 맞는 연산자를 선택하세요.

angular
import { from, interval } from 'rxjs';
import { switchMap, mergeMap, concatMap, exhaustMap } from 'rxjs/operators';

// switchMap: cancels the previous inner stream on new value
input$.pipe(switchMap(term => search(term)));
// Best for: typeahead search (discard stale results)

// mergeMap: runs all inner streams in parallel
ids$.pipe(mergeMap(id => fetchDetail(id)));
// Best for: parallel requests, order doesn't matter

// concatMap: queues inner streams, runs one at a time
queue$.pipe(concatMap(task => runTask(task)));
// Best for: ordered sequential operations

// exhaustMap: ignores new values while inner stream is active
save$.pipe(exhaustMap(() => saveForm()));
// Best for: prevent double-submit (ignore clicks while saving)
11

생명주기 훅

훅 실행 순서 개요

훅은 엄격한 순서로 실행됩니다. ngOnChanges는 @Input 변경 시(그리고 처음에) 실행됩니다. ngOnInit은 첫 ngOnChanges 후 한 번 실행됩니다. ngDoCheck는 모든 변경 감지 사이클에 실행됩니다. After* 훅은 콘텐츠/뷰가 DOM 조회 준비가 되었음을 알립니다. ngOnDestroy는 정리 지점입니다 — 구독 해제, 리소스 해제, 타이머 취소.

angular
export class LifecycleComponent implements
    OnChanges, OnInit, DoCheck, AfterContentInit,
    AfterContentChecked, AfterViewInit, AfterViewChecked, OnDestroy {

  ngOnChanges()    { console.log('1. input changes'); }
  ngOnInit()       { console.log('2. component init (once)'); }
  ngDoCheck()      { console.log('3. custom change detection'); }
  ngAfterContentInit()      { console.log('4. projected content ready'); }
  ngAfterContentChecked()   { console.log('5. projected content checked'); }
  ngAfterViewInit()         { console.log('6. view (template) ready'); }
  ngAfterViewChecked()      { console.log('7. view checked'); }
  ngOnDestroy()    { console.log('8. cleanup before destroy'); }
}

ngOnInit과 ngOnDestroy

ngOnInit은 input이 설정된 후 한 번 실행됩니다 — 데이터 가져오기, 구독 같은 무거운 초기화에 적합하며 생성자는 가볍게 유지해야 합니다. ngOnDestroy는 컴포넌트 파괴 시 호출되는 유일한 훅입니다 — 여기서 정리를 건너뛰면 구독, 타이머, 이벤트 리스너가 누출됩니다. 생성자는 DI 전용이고, 로직은 ngOnInit에 작성하세요.

angular
export class ChartComponent implements OnInit, OnDestroy {
  private timer?: ReturnType<typeof setInterval>;

  ngOnInit() {
    // good for: data fetching, initialization, subscriptions
    this.timer = setInterval(() => this.refresh(), 5000);
    this.loadInitialData();
  }

  ngOnDestroy() {
    // cleanup: clear timers, unsubscribe, release resources
    if (this.timer) clearInterval(this.timer);
    // also: this.sub.unsubscribe();
  }

  private refresh() { /* ... */ }
  private loadInitialData() { /* ... */ }
}

ngOnChanges (SimpleChange)

ngOnChanges는 @Input 참조가 바뀔 때마다 실행되며 SimpleChanges 맵을 받습니다: 각 항목은 previousValue, currentValue, firstChange, isFirstChange()를 가집니다. 객체의 프로퍼티를 변형할 때는 실행되지 않고 참조가 바뀔 때만 실행됩니다. 깊은 변경을 추적하려면 setter와 함께 사용하거나 IterableDiffers와 함께 ngDoCheck를 사용하세요.

angular
export class PaginationComponent implements OnChanges {
  @Input() page = 1;
  @Input() total = 0;

  ngOnChanges(changes: SimpleChanges) {
    if (changes['page'] && !changes['page'].firstChange) {
      // react only when page actually changed (not on init)
      console.log('page:', changes['page'].previousValue, '->', changes['page'].currentValue);
      this.fetchPage(this.page);
    }
  }

  private fetchPage(p: number) { /* ... */ }
}

ngAfterViewInit과 ViewChild

ViewChild/ContentChild 쿼리는 각각의 초기화 훅 이후에 해결됩니다. 컴포넌트 자체 템플릿의 엘리먼트는 ngAfterViewInit, <ng-content>로 투영된 콘텐츠는 ngAfterContentInit에서 접근합니다. ngOnInit에서 이 참조에 접근하면 undefined입니다. ! 널 아님 단언은 초기화 후 설정된다는 것을 컴파일러에 알려 주지만, After* 훅에서만 안전하게 사용할 수 있습니다.

angular
export class CanvasComponent implements AfterViewInit {
  @ViewChild('canvas') canvasRef!: ElementRef<HTMLCanvasElement>;

  // ❌ canvasRef is undefined in ngOnInit
  ngOnInit() { /* this.canvasRef is undefined here */ }

  // ✅ available after view init
  ngAfterViewInit() {
    const canvas = this.canvasRef.nativeElement;
    const ctx = canvas.getContext('2d');
    ctx?.fillText('Hello', 10, 50);
  }
}

// template: <canvas #canvas></canvas>

ngDoCheck (커스텀 감지)

ngDoCheck는 모든 변경 감지 사이클에 실행되므로 가볍게 유지해야 합니다. IterableDiffers/KeyValueDiffers를 사용하면 참조가 바뀌지 않는 배열/객체의 변형도 감지할 수 있습니다. 내부 변형 추적의 탈출구 역할을 합니다. 자주 실행되므로 무거운 로직은 피하세요 — 성능 문제를 일으킬 수 있습니다.

angular
export class ListComponent implements DoCheck {
  @Input() items: Item[] = [];
  private differ: IterableDiffer<Item>;

  constructor(differs: IterableDiffers) {
    this.differ = differs.find(items).create<Item>((i) => i.id);
  }

  ngDoCheck() {
    const changes = this.differ.diff(this.items);
    if (changes) {
      changes.forEachAddedItem(r => console.log('Added:', r.item));
      changes.forEachRemovedItem(r => console.log('Removed:', r.item));
    }
  }
}

콘텐츠 훅 vs 뷰 훅

콘텐츠 훅(AfterContentInit/Checked)은 <ng-content>로 투영된 콘텐츠에 실행됩니다. 뷰 훅(AfterViewInit/Checked)은 컴포넌트 자체 템플릿에 실행됩니다. 콘텐츠가 뷰 완료 전에 초기화되므로 콘텐츠 훅이 뷰 훅보다 먼저 실행됩니다. @ContentChild는 투영된 엘리먼트를, @ViewChild는 자체 템플릿 엘리먼트를 조회합니다.

angular
export class CardComponent implements
    AfterContentInit, AfterViewInit, AfterContentChecked, AfterViewChecked {

  @ContentChild('header') headerTpl?: TemplateRef<unknown>;
  @ViewChild('body') bodyEl?: ElementRef<HTMLElement>;

  // projected content (<ng-content>) is ready
  ngAfterContentInit() {
    console.log('content ready:', this.headerTpl);
  }

  // own template view is ready
  ngAfterViewInit() {
    console.log('view ready:', this.bodyEl?.nativeElement);
  }

  // ContentChecked/ViewChecked run every CD cycle after init — beware perf
}
12

콘텐츠 투영

기본 ng-content

<ng-content>는 부모가 제공한 콘텐츠가 투영되는 자리 표시자입니다. Angular의 <slot>이라고 생각하세요. select 없이는 모든 투영 콘텐츠가 여기에 들어갑니다. 투영된 콘텐츠는 부모 컨텍스트에서 컴파일됩니다 — {{ }} 같은 바인딩은 CardComponent가 아닌 부모 컴포넌트를 기준으로 해석됩니다.

angular
// card.component.ts
@Component({
  selector: 'app-card',
  template: `
    <div class="card">
      <ng-content></ng-content>
    </div>
  `,
  styles: ['.card { border: 1px solid #ccc; padding: 16px; }'],
})
export class CardComponent {}

<!-- usage: anything inside projects into <ng-content> -->
<app-card>
  <h3>Title</h3>
  <p>Body content here.</p>
</app-card>

멀티 슬롯 투영

ng-content의 select 속성은 특정 투영 콘텐츠를 대상으로 합니다: 엘리먼트('header'), 어트리뷰트('[header]'), 클래스('.active'), 또는 조합('div.foo[bar]'). 매칭되지 않은 콘텐츠는 select가 없는 ng-content로 들어갑니다. 투영된 콘텐츠는 부모의 스타일과 컨텍스트를 유지하며 DOM에서의 위치만 바뀝니다.

angular
@Component({
  selector: 'app-layout',
  template: `
    <header><ng-content select="[header]"></ng-content></header>
    <main><ng-content></ng-content></main>
    <footer><ng-content select="footer"></ng-content></footer>
  `,
})
export class LayoutComponent {}

<!-- usage: select matches attributes, elements, classes -->
<app-layout>
  <nav header>Top nav</nav>
  <p>Main body</p>
  <footer>Bottom</footer>
</app-layout>

조건부 투영 (ng-template)

조건부나 반복 투영에는 ng-template과 ngTemplateOutlet이 완전한 제어권을 줍니다. ContentChildren은 투영된 디렉티브를 조회합니다. ngTemplateOutlet은 TemplateRef를 원하는 위치에 렌더링합니다 — 탭, 아코디언, 조건부 슬롯에 유용합니다. 이 패턴은 콘텐츠 선언을 렌더링 위치/시점으로부터 분리합니다.

angular
@Component({
  selector: 'app-tabs',
  template: `
    <div class="tabs">
      @for (t of tabs; track t) {
        <button (click)="active = t">{{ t.title }}</button>
      }
    </div>
    @for (t of tabs; track t) {
      @if (t === active) {
        <ng-container [ngTemplateOutlet]="t.template" />
      }
    }
  `,
})
export class TabsComponent {
  @ContentChildren(TabDirective) tabs!: QueryList<TabDirective>;
  active: any;
}

ContentChild와 ContentChildren

@ContentChild / @ContentChildren은 투영된 콘텐츠를 조회합니다(자체 템플릿은 ViewChild). ContentChildren은 콘텐츠가 바뀔 때 갱신되는 QueryList를 반환합니다. ngAfterContentInit에서 해결됩니다. { descendants: true } 옵션(기본값)은 모든 투영 콘텐츠를 탐색합니다. { read: ... }로 ElementRef, TemplateRef 등 특정 타입을 조회할 수 있습니다.

angular
@Directive({ selector: 'tab' })
export class TabDirective {
  @Input() title = '';
  @Input() active = false;
  @ContentChild(TemplateRef) template!: TemplateRef<unknown>;
}

@Component({
  selector: 'app-tabset',
  template: `
    @for (tab of tabs; track tab) {
      <button (click)="select(tab)">{{ tab.title }}</button>
    }
    <ng-container *ngTemplateOutlet="activeTab?.template" />
  `,
})
export class TabsetComponent implements AfterContentInit {
  @ContentChildren(TabDirective) tabs!: QueryList<TabDirective>;
  activeTab?: TabDirective;

  ngAfterContentInit() {
    this.activeTab = this.tabs.find(t => t.active) ?? this.tabs.first;
  }
}

컨텍스트를 포함한 ngTemplateOutlet

ngTemplateOutlet은 선택적 컨텍스트와 함께 TemplateRef를 렌더링합니다. let-x는 context.$implicit(기본값)에 바인딩되고, let-y='key'는 context.key에 바인딩됩니다. *ngFor와 ngTemplateOutlet이 반복 변수를 전달하는 방식이 바로 이것입니다. 컴포넌트가 반복 로직을 제어하면서 부모가 커스터마이즈할 수 있는 재사용 가능한 목록/그리드/아이템 템플릿에 이 패턴을 사용하세요.

angular
@Component({
  selector: 'app-list',
  template: `
    @for (item of items; track item.id) {
      <ng-container *ngTemplateOutlet="itemTpl; context: { $implicit: item, i: $index }" />
    }
    <ng-template #itemTpl let-item let-i="i">
      <li>{{ i }}: {{ item.name }}</li>
    </ng-template>
  `,
})
export class ListComponent {
  items = [{ id: 1, name: 'A' }, { id: 2, name: 'B' }];
}

ng-content select 패턴

select는 CSS 비슷한 셀렉터를 받습니다: 클래스(.x), 어트리뷰트([x]), 엘리먼트(header), 쉼표 목록('a, b'). 어떤 셀렉터와도 일치하지 않는 콘텐츠는 select가 없는 ng-content로 들어가고, 폴백이 없으면 버려집니다. 셀렉터는 투영된 엘리먼트 자신의 어트리뷰트에 매칭되며, 내부 구조에는 매칭되지 않습니다.

angular
@Component({
  selector: 'app-modal',
  template: `
    <div class="modal">
      <ng-content select=".modal-header"></ng-content>
      <ng-content select="[body]"></ng-content>
      <ng-content select="app-modal-footer, footer"></ng-content>
      <!-- fallback for unmatched content -->
      <ng-content></ng-content>
    </div>
  `,
})

<!-- matches by class, attribute, element, or selector list -->
<app-modal>
  <div class="modal-header">Title</div>
  <section body>Body text</section>
  <app-modal-footer>OK</app-modal-footer>
  <p>This falls into the unselect'd slot.</p>
</app-modal>
13

라우트 가드

CanActivate (함수형)

함수형 가드(v14.2+)는 true/false/UrlTree 또는 이들의 Observable/Promise를 반환합니다. UrlTree를 반환하면 해당 라우트로 리다이렉트됩니다. 가드는 주입 컨텍스트에서 실행되므로 inject()를 쓸 수 있습니다. CanActivate는 라우트로의 내비게이션을 막습니다. canActivate 배열에 라우트별로 등록하며, 해당 라우트로 내비게이션할 때마다 실행됩니다.

angular
import { inject } from '@angular/core';
import { CanActivateFn, Router } from '@angular/router';

export const authGuard: CanActivateFn = (route, state) => {
  const auth = inject(AuthService);
  const router = inject(Router);

  if (auth.isLoggedIn) return true;

  // redirect to login, preserving the attempted URL
  return router.createUrlTree(['/login'], {
    queryParams: { returnUrl: state.url },
  });
};

// register in routes
{ path: 'dashboard', component: DashboardComponent, canActivate: [authGuard] }

CanActivateChild

CanActivateChild는 부모 아래 각 자식 라우트 전에 실행됩니다 — 모든 자식에 canActivate를 반복하는 것보다 깔끔합니다. 기능 영역 전체를 공통으로 보호할 때 사용하세요. 반환 타입은 CanActivate와 같습니다. 부모 자체도 보호하려면 부모 라우트에도 canActivate를 추가하세요.

angular
export const adminGuard: CanActivateChildFn = (route, state) => {
  const auth = inject(AuthService);

  if (!auth.isAdmin) {
    return inject(Router).parseUrl('/forbidden');
  }
  return true;
};

// applies to all children of this route
{
  path: 'admin',
  canActivateChild: [adminGuard],
  children: [
    { path: 'users', component: AdminUsersComponent },
    { path: 'settings', component: AdminSettingsComponent },
  ],
}

CanDeactivate (저장되지 않은 변경 가드)

CanDeactivate는 라우트를 떠나기 전에 실행됩니다 — 저장하지 않은 폼 변경에 경고하기에 완벽합니다. 가드는 컴포넌트 인스턴스를 받으므로 그 메서드를 호출합니다. false를 반환하면 내비게이션이 취소되고 true면 진행됩니다. 비동기(모달 확인)의 경우 Observable이나 Promise를 반환하세요. 컴포넌트는 가드가 기대하는 계약을 구현해야 합니다.

angular
import { CanDeactivateFn } from '@angular/router';
import { inject } from '@angular/core';

export interface CanComponentDeactivate {
  canDeactivate: () => boolean | Observable<boolean>;
}

export const unsavedGuard: CanDeactivateFn<CanComponentDeactivate> = (component) => {
  return component?.canDeactivate() ?? true;
};

// component
export class EditComponent implements CanComponentDeactivate {
  canDeactivate() {
    if (this.form.dirty) return confirm('Discard changes?');
    return true;
  }
}

// route: { path: 'edit/:id', canDeactivate: [unsavedGuard] }

CanMatch (조건부 로딩)

CanMatch(v14.1+)는 lazy 라우트의 청크가 다운로드되기도 전에 실행됩니다 — 유료 기능 게이팅에 CanActivate보다 효율적입니다. false를 반환하면 라우트가 완전히 건너뛰어집니다(다른 매칭 라우트에 기회가 갑니다). CanActivate는 청크를 먼저 로드한 뒤 거부합니다. 사용자가 접근할 수 없는 코드의 다운로드를 막으려면 CanMatch를 사용하세요.

angular
import { CanMatchFn } from '@angular/router';

export const paidFeatureGuard: CanMatchFn = (route, segments) => {
  const auth = inject(AuthService);
  // runs BEFORE the lazy chunk is even loaded
  if (auth.hasProPlan) return true;

  return inject(Router).createUrlTree(['/upgrade']);
};

// route configuration
{
  path: 'premium',
  canMatch: [paidFeatureGuard],
  loadComponent: () => import('./premium/premium.component'),
}

Resolve (데이터 프리페치)

Resolve는 라우트가 활성화되기 전에 실행되어 데이터가 도착할 때까지 내비게이션을 지연시킵니다. 해결된 데이터는 route.snapshot.data에 담깁니다. 렌더링 시 컴포넌트가 데이터를 갖도록 보장합니다(빈 상태 깜빡임 없음). 오류는 리졸버 내부에서 처리하세요 — EMPTY를 반환하면 내비게이션이 취소됩니다. 블로킹하지 않으려면 대신 ngOnInit에서 가져오세요.

angular
import { ResolveFn } from '@angular/router';
import { inject } from '@angular/core';

export const userResolver: ResolveFn<User> = (route) => {
  const id = route.paramMap.get('id')!;
  return inject(UserService).getUser(+id).pipe(
    catchError(() => {
      inject(Router).navigate(['/users']);
      return EMPTY;
    }),
  );
};

// route
{ path: 'users/:id', resolve: { user: userResolver }, component: UserComponent }

// component reads pre-fetched data
export class UserComponent {
  user = this.route.snapshot.data['user'] as User;
  constructor(private route: ActivatedRoute) {}
}

가드 조합과 순서

여러 가드는 배열 순서대로 실행되며, 처음 실패하는 가드가 내비게이션을 취소합니다. canMatch는 lazy 청크 로드 전에, canActivate는 그 후에 실행됩니다. canDeactivate는 떠날 때 실행됩니다. 모든 가드는 동기(boolean 반환) 또는 비동기(Observable/Promise)일 수 있습니다. UI를 막으므로 빠르게 유지하고, 무거운 서버 검사는 디바운스하거나 결과를 캐싱하세요.

angular
// multiple guards run in declaration order, all must pass
{
  path: 'admin',
  canActivate: [authGuard, roleGuard],
  canMatch: [paidFeatureGuard],
  canDeactivate: [unsavedGuard],
  loadChildren: () => import('./admin/admin.routes'),
}

// guard returning Observable (async check)
export const roleGuard: CanActivateFn = () => {
  return inject(AuthService).hasRole('admin').pipe(
    map(ok => ok || inject(Router).parseUrl('/forbidden')),
  );
};

// ordering: canMatch → resolve → canActivate → canActivateChild
14

리졸버(Resolvers)

기본 리졸버 (ResolveFn)

ResolveFn은 함수형 리졸버 API입니다. 내비게이션이 완료되기 전에 실행되며, 반환 값이 지정한 키로 route.data에 담깁니다. 컴포넌트는 snapshot.data에서 동기적으로 읽을 수 있어 로딩 상태가 필요 없습니다. 같은 컴포넌트의 라우트 간 이동 시 반응형 업데이트를 원하면 route.data를 구독하세요.

angular
import { ResolveFn } from '@angular/router';
import { inject } from '@angular/core';

export const postResolver: ResolveFn<Post> = (route, state) => {
  const id = Number(route.paramMap.get('id'));
  return inject(PostService).getPost(id);
};

// route
{
  path: 'posts/:id',
  resolve: { post: postResolver },
  component: PostDetailComponent,
}

// reading the resolved data
export class PostDetailComponent {
  post = this.route.snapshot.data['post'] as Post;
  constructor(private route: ActivatedRoute) {}

  // reactive: re-fetch when :id changes (same component reused)
  ngOnInit() {
    this.route.data.subscribe(d => this.post = d['post']);
  }
}

여러 리졸버

여러 리졸버는 병렬로 실행되며 모두 완료되어야 라우트가 활성화됩니다. resolve의 각 키가 route.data의 키가 됩니다. 하나라도 실패하면 내비게이션이 취소됩니다. 독립적인 데이터라면 효율적입니다. 의존 관계가 있다면 중첩하거나 단일 리졸버에서 체이닝하세요. 리졸버와 ngOnInit fetch의 트레이드오프를 고려하세요.

angular
{
  path: 'dashboard',
  component: DashboardComponent,
  resolve: {
    user: userResolver,
    stats: statsResolver,
    notifications: notifResolver,
  },
}

// component
export class DashboardComponent {
  constructor(private route: ActivatedRoute) {}
  ngOnInit() {
    const { user, stats, notifications } = this.route.snapshot.data;
    // all three resolved before component loads
  }
}

리졸버 오류 처리

리졸버 오류는 명시적으로 처리하세요 — 처리되지 않은 오류는 내비게이션을 조용히 취소합니다. EMPTY는 방출 없이 스트림을 완료해 내비게이션을 취소합니다. null을 반환하면 컴포넌트가 누락된 데이터를 우아하게 처리할 수 있습니다. 404는 not-found 라우트로 리다이렉트하세요. 오류는 항상 기록하거나 표면화하세요 — 조용한 실패는 사용자가 디버깅하기 어렵습니다.

angular
export const userResolver: ResolveFn<User | null> = (route) => {
  const id = route.paramMap.get('id')!;
  const router = inject(Router);
  const service = inject(UserService);

  return service.getUser(+id).pipe(
    catchError(err => {
      if (err.status === 404) {
        // redirect to a 'not found' page, cancel navigation
        router.navigate(['/404']);
        return EMPTY;
      }
      // re-throw other errors
      return throwError(() => err);
    }),
  );
};

리졸버 vs ngOnInit fetch

리졸버는 데이터가 도착할 때까지 내비게이션을 막습니다 — UX는 깔끔하지만 느리게 느껴질 수 있습니다. ngOnInit fetch는 블로킹하지 않지만 컴포넌트에 로딩 상태가 필요합니다. 모던 Angular 가이드는 비블로킹을 지향합니다 — 로딩 스켈레톤과 함께 컴포넌트에서 가져오면 체감 성능이 좋습니다. 데이터 없이는 정말 렌더링할 수 없을 때만 리졸버를 사용하세요.

angular
// Approach A: Resolver (blocks navigation until data arrives)
// ✅ Component renders with data — no flicker
// ❌ Slower navigation feel, blocks route transition
{
  path: 'user/:id',
  resolve: { user: userResolver },
  component: UserComponent,
}

// Approach B: Fetch in ngOnInit (non-blocking)
// ✅ Snappy navigation, show loading skeleton
// ❌ Component must handle null/loading state
export class UserComponent implements OnInit {
  user?: User;
  loading = true;
  ngOnInit() {
    this.route.params.subscribe(p => {
      this.loading = true;
      this.svc.getUser(+p['id']).subscribe(u => {
        this.user = u;
        this.loading = false;
      });
    });
  }
}

쿼리 파라미터와 시그널을 활용한 리졸버

리졸버는 라우트에서 paramMap과 queryParamMap을 모두 읽을 수 있습니다. 같은 컴포넌트가 다른 파라미터를 처리할 때는 snapshot 대신 route.data를 반응형으로 구독하세요. 시그널을 사용한다면 데이터 구독에서 시그널을 업데이트하세요. 리졸버와 시그널을 조합하면 깔끔한 반응형 데이터 흐름이 됩니다. 내비게이션을 막으므로 무거운 리졸버는 피하세요.

angular
// read query params inside a resolver
export const searchResolver: ResolveFn<SearchResult[]> = (route) => {
  const q = route.queryParamMap.get('q') ?? '';
  const page = Number(route.queryParamMap.get('page') ?? 1);
  return inject(SearchService).search(q, page);
};

// resolver feeding a signal-based component
export class SearchComponent {
  private route = inject(ActivatedRoute);
  results = signal<SearchResult[]>([]);

  constructor() {
    this.route.data.subscribe(d => this.results.set(d['results']));
  }
}
15

애니메이션

설정과 기본 애니메이션

provideAnimations()가 애니메이션 모듈을 등록합니다. trigger()는 이름 있는 애니메이션을 정의하고, transition()은 상태 간 변화를 선언합니다. :enter와 :leave는 *ngIf나 @if로 추가/제거되는 엘리먼트를 위한 내장 의사 상태입니다. 템플릿에서 @triggerName으로 적용합니다. v17+ 제어 흐름에서도 @if/@for와 함께 애니메이션이 동작합니다.

angular
// app.config.ts
import { provideAnimations } from '@angular/platform-browser/animations';
export const appConfig: ApplicationConfig = {
  providers: [provideAnimations()],
};

// component
@Component({
  selector: 'app-fade',
  animations: [
    trigger('fadeIn', [
      transition(':enter', [
        style({ opacity: 0 }),
        animate('300ms ease-in', style({ opacity: 1 })),
      ]),
      transition(':leave', [
        animate('300ms ease-out', style({ opacity: 0 })),
      ]),
    ]),
  ],
  template: `<div *ngIf="show" @fadeIn>Hello</div>`,
})

상태와 트랜지션

state()는 정지 상태의 스타일을 정의합니다. transition('a => b')는 상태 a에서 b로 애니메이션하고, '<=>'는 양방향입니다. 트리거를 상태 이름을 반환하는 표현식에 바인딩하세요. 상태 스타일은 즉시 적용되고(애니메이션 없음), 트랜지션이 그 사이를 애니메이션합니다. 아직 DOM에 없는 엘리먼트는 'void', 와일드카드는 '*'를 사용합니다.

angular
@Component({
  selector: 'app-toggle',
  animations: [
    trigger('openClose', [
      state('open', style({ height: '*', opacity: 1 })),
      state('closed', style({ height: '0', opacity: 0 })),
      transition('open => closed', animate('200ms ease-out')),
      transition('closed => open', animate('300ms ease-in')),
      // bidirectional shortcut: 'open <=> closed'
    ]),
  ],
  template: `
    <button (click)="isOpen = !isOpen">Toggle</button>
    <div [@openClose]="isOpen ? 'open' : 'closed'">Panel</div>
  `,
})
export class ToggleComponent { isOpen = false; }

키프레임과 병렬 애니메이션

keyframes()는 offset(0~1)으로 중간 단계를 정의해 세밀한 제어를 제공합니다 — CSS @keyframes와 같습니다. group()은 애니메이션을 병렬로, sequence()는 순차적으로 실행합니다. 복잡한 등장/퇴장 효과를 조합할 때 사용하세요. 애니메이션은 짧게(200~400ms) 유지하고 접근성을 위해 prefers-reduced-motion을 존중하세요.

angular
trigger('wiggle', [
  transition('* => *', [
    animate('600ms ease-in-out', keyframes([
      style({ transform: 'translateX(0)', offset: 0 }),
      style({ transform: 'translateX(-10px)', offset: 0.25 }),
      style({ transform: 'translateX(10px)', offset: 0.75 }),
      style({ transform: 'translateX(0)', offset: 1 }),
    ])),
  ]),
]),

// parallel/group animations
transition(':enter', [
  group([
    animate('300ms', style({ opacity: 1 })),
    animate('300ms', style({ transform: 'translateY(0)' })),
  ]),
]),

애니메이션 목록 (@for)

@for 아이템에 :enter/:leave 애니메이션을 적용하면 항목이 추가/제거될 때 실행됩니다. track이 Angular가 변경 사이에서 항목을 올바르게 식별하게 해 주므로, 애니메이션이 실제 추가/제거에서 실행됩니다(재정렬이 아님). 적절한 track이 없으면 목록 애니메이션이 버벅일 수 있습니다. 재정렬 애니메이션에는 query()와 animateChild()를 사용하세요.

angular
@Component({
  selector: 'app-list',
  animations: [
    trigger('itemAnim', [
      transition(':enter', [
        style({ height: 0, opacity: 0 }),
        animate('200ms', style({ height: '*', opacity: 1 })),
      ]),
      transition(':leave', [
        animate('200ms', style({ height: 0, opacity: 0 })),
      ]),
    ]),
  ],
  template: `
    @for (item of items; track item.id) {
      <div @itemAnim>{{ item.name }}</div>
    }
  `,
})
export class AnimListComponent { items = [...]; }

라우터 애니메이션

애니메이션 트리거를 router-outlet의 활성화 상태에 바인딩합니다. query(':enter'/:leave)가 들어오고 나가는 라우팅 컴포넌트를 대상으로 합니다. { optional: true }는 한쪽이 없을 때의 오류를 방지합니다(초기 로드에는 :leave가 없음). position: absolute는 트랜지션 동안 이전/새 컴포넌트를 겹치게 합니다. 라우트 애니메이션으로 앱 같은 뷰 전환을 만들 수 있습니다.

angular
@Component({
  selector: 'app-root',
  animations: [
    trigger('routeAnim', [
      transition('* => *', [
        query(':enter', [
          style({ opacity: 0, position: 'absolute', width: '100%' }),
          animate('300ms', style({ opacity: 1 })),
        ], { optional: true }),
        query(':leave', [
          animate('300ms', style({ opacity: 0 })),
        ], { optional: true }),
      ]),
    ]),
  ],
  template: `
    <div [@routeAnim]="o.isActivated ? o.activatedRoute : ''">
      <router-outlet #o="outlet"></router-outlet>
    </div>
  `,
})

모션 감소와 CSS 애니메이션

접근성을 위해 항상 prefers-reduced-motion을 존중하세요 — 어떤 사용자는 멀미를 겪습니다. Angular 애니메이션은 번들에 약 50KB를 추가하므로 단순 페이드에는 일반 CSS 애니메이션으로 충분할 수 있습니다. 상태 기반 전환(상태 머신), 부모-자식 조율, 라우트 애니메이션이 필요할 때 Angular 애니메이션을 사용하세요. hover/페이드 효과는 CSS가 더 가볍습니다.

angular
// respect prefers-reduced-motion
@Component({
  selector: 'app-safe-anim',
  animations: [
    trigger('fade', [
      transition(':enter', [
        style({ opacity: 0 }),
        animate('300ms', style({ opacity: 1 })),
      ]),
    ]),
  ],
  // or just use CSS — Angular animations add bundle weight
  template: `<div class="fade-in" @fade>Content</div>`,
  styles: [`
    @media (prefers-reduced-motion: reduce) {
      .fade-in { animation: none !important; transition: none !important; }
    }
  `],
})
16

테스팅

컴포넌트 테스트 설정

TestBed가 테스팅 모듈을 구성합니다. standalone 컴포넌트는 직접 임포트합니다(TestBed.configureTestingModule의 declarations 불필요). createComponent는 ComponentFixture를 반환합니다: 클래스는 .componentInstance, DOM은 .nativeElement, 변경 감지 트리거는 .detectChanges()를 사용합니다. async/await와 함께 beforeEach가 compileComponents를 처리합니다.

angular
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { MyComponent } from './my.component';

describe('MyComponent', () => {
  let fixture: ComponentFixture<MyComponent>;
  let component: MyComponent;

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      imports: [MyComponent],   // standalone components are imported
    }).compileComponents();

    fixture = TestBed.createComponent(MyComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();   // runs initial change detection
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});

목 서비스로 테스트

테스트 대상 컴포넌트를 격리하려면 서비스의 목 구현을 제공하세요. jasmine.createSpy()로 반환 값을 제어하고 호출을 검증할 수 있습니다. 객체 목에는 useValue, 클래스 기반 가짜에는 useClass를 사용합니다. HTTP 테스트에서는 HttpClient를 HttpTestingController로 오버라이드하세요. 목킹은 실제 네트워크 호출 없이 테스트를 빠르고 결정적으로 유지합니다.

angular
describe('UserComponent', () => {
  let mockUserService = {
    getUsers: jasmine.createSpy().and.returnValue(of([...])),
    addUser: jasmine.createSpy().and.returnValue(of({})),
  };

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      imports: [UserComponent],
      providers: [
        { provide: UserService, useValue: mockUserService },
      ],
    }).compileComponents();
  });

  it('loads users on init', () => {
    const fixture = TestBed.createComponent(UserComponent);
    fixture.detectChanges();
    expect(mockUserService.getUsers).toHaveBeenCalled();
    expect(fixture.componentInstance.users.length).toBe(2);
  });
});

HTTP 테스팅

HttpTestingController는 테스트에서 HttpClient 호출을 가로챕니다 — 실제 네트워크가 없습니다. expectOne은 요청이 있었음을 검증하고 그 요청을 반환하며, flush()가 서버 응답을 시뮬레이션합니다. verify()는 매칭되지 않은 요청이 없음을 보장합니다. 성공과 오류 경로를 모두 테스트하세요: 상태 코드와 함께 flush하면(예: { status: 500, statusText: 'Server Error' }) 오류를 시뮬레이션합니다.

angular
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { provideHttpClient } from '@angular/common/http';

describe('PostService', () => {
  let service: PostService;
  let httpMock: HttpTestingController;

  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [
        PostService,
        provideHttpClient(),
        provideHttpClientTesting(),
      ],
    });
    service = TestBed.inject(PostService);
    httpMock = TestBed.inject(HttpTestingController);
  });

  it('fetches posts', () => {
    service.getPosts().subscribe(posts => expect(posts.length).toBe(2));

    const req = httpMock.expectOne('/api/posts');
    expect(req.request.method).toBe('GET');
    req.flush([{ id: 1 }, { id: 2 }]);   // simulate response
    httpMock.verify();                    // no outstanding requests
  });
});

템플릿과 상호작용 테스팅

fixture.nativeElement로 DOM에 직접 접근해 검증합니다. 프로퍼티를 설정한 후 detectChanges()가 템플릿 바인딩을 동기화합니다. spyOn으로 메서드 호출을 검증할 수 있습니다. 컴포넌트 내부 조회에는 debugElement.query(By.css())가 타입 안전합니다. 이벤트는 네이티브 DOM 메서드(click())나 커스텀 이벤트용 DebugElement.triggerEventHandler로 트리거합니다.

angular
it('renders the title', () => {
  const fixture = TestBed.createComponent(MyComponent);
  fixture.componentInstance.title = 'Hello';
  fixture.detectChanges();
  const el: HTMLElement = fixture.nativeElement;
  expect(el.querySelector('h1')?.textContent).toContain('Hello');
});

it('calls save on button click', () => {
  const fixture = TestBed.createComponent(MyComponent);
  const spy = spyOn(fixture.componentInstance, 'save');
  const button = fixture.nativeElement.querySelector('button');
  button.click();
  expect(spy).toHaveBeenCalled();
});

// By.css for debug element queries (faster than nativeElement)
const debugEl = fixture.debugElement.query(By.css('.submit'));

시그널 테스팅

시그널은 함수입니다 — 테스트에서 값을 읽으려면 괄호와 함께 호출하세요. set()으로 쓰기 가능한 시그널을 직접 업데이트하면 간접 조작이 필요 없습니다. detectChanges()가 시그널 기반 템플릿을 동기화합니다. computed/effect의 경우 detectChanges나 TestBed.flushEffects()로 의존 effect의 실행을 보장합니다. 시그널은 테스트를 더 동기적이고 예측 가능하게 만듭니다.

angular
describe('CounterComponent', () => {
  it('increments count', () => {
    const fixture = TestBed.createComponent(CounterComponent);
    const comp = fixture.componentInstance;

    expect(comp.count()).toBe(0);
    comp.increment();
    expect(comp.count()).toBe(1);

    // force signal effects to run in tests
    fixture.detectChanges();
  });

  it('renders count in template', () => {
    const fixture = TestBed.createComponent(CounterComponent);
    fixture.componentInstance.count.set(5);
    fixture.detectChanges();   // syncs signal to template
    expect(fixture.nativeElement.textContent).toContain('5');
  });
});

Cypress / Playwright E2E

E2E 테스트는 실제 브라우저로 앱 전체를 시험합니다. 셀렉터에는 data-cy 어트리뷰트를 사용하세요 — 안정적이고 CSS 클래스에 결합되지 않습니다. Cypress는 브라우저 내에서 실행되고 Playwright는 여러 브라우저에서 실행됩니다. ng e2e를 사용하거나 Cypress/Playwright를 수동으로 설정하세요. E2E는 단위 테스트가 놓치는 통합 문제를 잡지만 느립니다 — 스위트를 핵심에 집중하세요.

angular
// cypress test (cypress/e2e/login.cy.ts)
describe('Login flow', () => {
  beforeEach(() => cy.visit('/login'));

  it('logs in with valid credentials', () => {
    cy.get('[data-cy=email]').type('[email protected]');
    cy.get('[data-cy=password]').type('secret123');
    cy.get('[data-cy=submit]').click();

    cy.url().should('include', '/dashboard');
    cy.contains('Welcome, User');
  });
});

// run with: npx cypress open  (interactive)
//           npx cypress run   (headless CI)
17

PWA

PWA 지원 추가

ng add @angular/pwa가 서비스 워커 등록, 웹 매니페스트, 아이콘을 모두 스캐폴딩합니다. 서비스 워커는 프로덕션 빌드(ng build --configuration production)에서만 실행됩니다 — 캐싱 놀라움을 피하려고 개발 중에는 비활성화됩니다. registrationStrategy가 SW 등록 시점을 제어하며, registerWhenStable은 앱이 안정화되기를 기다립니다.

angular
# add @angular/service-worker
ng add @angular/pwa --project my-app

# this generates:
# - ngsw-config.json (service worker config)
# - manifest.webmanifest
# - icons in src/assets/icons/
# - registers service worker in app.config.ts

# app.config.ts (auto-updated)
export const appConfig: ApplicationConfig = {
  providers: [
    provideRouter(routes),
    provideServiceWorker('ngsw-worker.js', {
      enabled: environment.production,
      registrationStrategy: 'registerWhenStable:30000',
    }),
  ],
};

서비스 워커 설정 (ngsw-config.json)

assetGroups는 앱 셸(prefetch)과 정적 자산(lazy)을 캐싱합니다. dataGroups는 신선도/성능 전략과 TTL로 API 응답을 캐싱합니다. prefetch는 미리 다운로드하고, lazy는 필요할 때 다운로드합니다. freshness는 네트워크 우선, 실패 시 캐시(신선한 데이터에 좋음)이고, performance는 캐시 우선(거의 정적인 데이터에 좋음)입니다.

angular
{
  "$schema": "./node_modules/@angular/service-worker/config/schema.json",
  "index": "/index.html",
  "assetGroups": [
    {
      "name": "app",
      "installMode": "prefetch",
      "updateMode": "prefetch",
      "resources": {
        "files": ["/favicon.ico", "/index.html", "/manifest.webmanifest", "/*.css", "/*.js"]
      }
    },
    {
      "name": "assets",
      "installMode": "lazy",
      "updateMode": "prefetch",
      "resources": { "files": ["/assets/**", "/*.(svg|png|jpg|jpeg|webp|woff2)"] }
    }
  ],
  "dataGroups": [
    {
      "name": "api",
      "urls": ["https://api.example.com/**"],
      "cacheConfig": {
        "maxSize": 100, "maxAge": "1d", "timeout": "10s", "strategy": "freshness"
      }
    }
  ]
}

업데이트 처리

SwUpdate는 새 버전이 준비되면 알려 줍니다. VERSION_READY는 새 번들이 다운로드되어 활성화 준비가 되었음을 의미합니다. activateUpdate()로 새 버전으로 교체하고, 적용하려면 reload하세요. 중요한 업데이트는 즉시 강제 활성화하고, 그렇지 않으면 사용자에게 확인을 요청하세요. versionUpdates를 구독해 VERSION_DETECTED, VERSION_READY, NO_NEW_VERSION_DETECTED를 처리합니다.

angular
import { SwUpdate } from '@angular/service-worker';
import { inject } from '@angular/core';

export class UpdatePromptComponent {
  private updates = inject(SwUpdate);
  updateAvailable = false;

  constructor() {
    this.updates.versionUpdates.subscribe(evt => {
      if (evt.type === 'VERSION_READY') {
        this.updateAvailable = true;
      }
    });
  }

  applyUpdate() {
    this.updates.activateUpdate().then(() => document.location.reload());
  }
}

오프라인 지원과 캐싱

SwPush는 서비스 워커를 통한 웹 푸시 알림을 지원합니다. requestSubscription은 사용자 권한을 요청하고 서버로 보낼 구독 객체를 반환합니다. SW는 탭이 닫혀도 push 이벤트를 받습니다. VAPID 키가 서버를 인증합니다. 메시지 표시는 Notification API와 함께 쓰고, 클릭 처리로 앱 내 내비게이션을 하세요.

angular
import { SwPush } from '@angular/service-worker';

export class NotificationComponent {
  private swPush = inject(SwPush);

  subscribeToPush() {
    this.swPush.requestSubscription({
      serverPublicKey: this.VAPID_PUBLIC,
    }).then(sub => this.sendToServer(sub))
      .catch(err => console.error('Push denied', err));
  }

  // check if SW is enabled
  ngOnInit() {
    if (!this.swPush.isEnabled) {
      console.warn('Push notifications not supported');
    }
  }
}

앱 매니페스트

웹 매니페스트는 앱을 설치 가능하게 만듭니다(홈 화면에 추가). name/short_name은 홈 화면에 표시되고, theme_color는 브라우저 UI를 물들이며, display: standalone은 브라우저 크롬을 제거해 앱 같은 느낌을 줍니다. 여러 아이콘 크기(192, 512)와 Android용 maskable 아이콘을 제공하세요. Lighthouse의 PWA 감사로 설치 가능 여부를 확인할 수 있습니다.

angular
<!-- index.html (added by ng add @angular/pwa) -->
<link rel="manifest" href="manifest.webmanifest">
<meta name="theme-color" content="#1976d2">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<link rel="apple-touch-icon" href="assets/icons/icon-152x152.png">

// manifest.webmanifest
{
  "name": "My App",
  "short_name": "MyApp",
  "theme_color": "#1976d2",
  "background_color": "#fafafa",
  "display": "standalone",
  "scope": "/",
  "start_url": "/",
  "icons": [
    { "src": "assets/icons/icon-192x192.png", "sizes": "192x192", "type": "image/png" },
    { "src": "assets/icons/icon-512x512.png", "sizes": "512x512", "type": "image/png" }
  ]
}

설치 가능성과 Lighthouse

beforeinstallprompt는 Chrome에서 앱이 설치 가능할 때 발생하며, 네이티브 프롬프트를 미룰 수 있게 해 줍니다. 이벤트를 저장했다가 사용자 제스처(버튼 클릭)에서 prompt()를 호출하세요. iOS Safari는 이 이벤트가 발생하지 않습니다 — 사용자는 공유 메뉴에서 설치합니다. Lighthouse의 PWA 감사로 설치 가능성을 확인하세요. PWA가 오프라인으로 동작하려면 서비스 워커가 앱 셸을 캐싱해야 합니다.

angular
// detect install prompt (Chrome)
let deferredPrompt: any;
window.addEventListener('beforeinstallprompt', (e) => {
  e.preventDefault();
  deferredPrompt = e;
  this.canInstall = true;   // show "Install App" button
});

// user-triggered install (must be from user gesture)
async installApp() {
  if (!deferredPrompt) return;
  deferredPrompt.prompt();
  const { outcome } = await deferredPrompt.userChoice;
  console.log('Install:', outcome);
  deferredPrompt = null;
}

// Lighthouse PWA checklist:
// ✅ served over HTTPS
// ✅ registers a service worker
// ✅ has a web manifest with icons
// ✅ start_url loads offline
18

Standalone 컴포넌트

standalone 부트스트랩

bootstrapApplication은 standalone 앱을 시작합니다 — NgModule이 필요 없습니다. 루트 AppComponent는 standalone이어야 합니다. app.config.ts가 프로바이더(라우터, http, 애니메이션, zone 설정)를 중앙 집중화합니다. v17부터 기본 방식입니다. 각 provideX() 함수가 하위 시스템을 연결합니다. AppModule + 프로바이더보다 훨씬 깔끔합니다.

angular
// main.ts
import { bootstrapApplication } from '@angular/platform-browser';
import { appConfig } from './app/app.config';
import { AppComponent } from './app/app.component';

bootstrapApplication(AppComponent, appConfig)
  .catch(err => console.error(err));

// app.config.ts
import { ApplicationConfig, provideZoneChangeDetection } from '@angular/core';
import { provideRouter } from '@angular/router';
import { provideHttpClient } from '@angular/common/http';
import { routes } from './app.routes';

export const appConfig: ApplicationConfig = {
  providers: [
    provideZoneChangeDetection({ eventCoalescing: true }),
    provideRouter(routes),
    provideHttpClient(),
  ],
};

standalone 컴포넌트 임포트

standalone: true는 컴포넌트가 자기 완결적임을 표시합니다. imports 배열에는 템플릿에 필요한 모든 것(모듈, 컴포넌트, 디렉티브, 파이프)을 나열합니다. v17+ 제어 흐름(@if/@for)을 사용하면 그것들에는 CommonModule이 필요 없습니다. 사용하는 것만 임포트하면 tree-shaking에 유리합니다. standalone 컴포넌트는 exports를 통해 NgModule에서도 사용할 수 있습니다.

angular
@Component({
  selector: 'app-user-list',
  standalone: true,
  imports: [
    CommonModule,          // *ngIf, *ngFor, pipes (or use built-in @if/@for)
    FormsModule,           // ngModel
    UserCardComponent,     // another standalone component
    HighlightDirective,    // standalone directive
    TruncatePipe,          // standalone pipe
  ],
  template: `
    <input [(ngModel)]="filter" />
    @for (u of users; track u.id) {
      <app-user-card [user]="u" appHighlight>{{ u.name | truncate:20 }}</app-user-card>
    }
  `,
})
export class UserListComponent { ... }

standalone 라우트와 lazy loading

loadComponent는 standalone 컴포넌트 하나를 lazy 로드합니다 — 가장 작은 청크입니다. loadChildren은 라우트 파일(Routes의 default export)을 lazy 로드합니다. 둘 다 번들러가 분할하도록 dynamic import()에 정적 경로를 사용합니다. 이것이 기능 모듈을 완전히 대체합니다. 각 lazy 라우트는 자체 JS 파일로, 첫 내비게이션 시 로드됩니다.

angular
export const routes: Routes = [
  { path: '', loadComponent: () => import('./home/home.component')
      .then(m => m.HomeComponent) },
  {
    path: 'admin',
    loadComponent: () => import('./admin/admin.component')
      .then(m => m.AdminComponent),
    canMatch: [authGuard],
  },
  {
    path: 'reports',
    loadChildren: () => import('./reports/reports.routes')
      .then(m => m.REPORTS_ROUTES),
  },
];

standalone으로서의 디렉티브와 파이프

디렉티브와 파이프도 standalone일 수 있습니다(v15+). standalone: true를 추가하고 필요한 컴포넌트 어디서든 임포트하세요. 공유 모듈에 선언할 필요가 사라집니다. 하위 호환을 위해 standalone 디렉티브/파이프는 NgModule exports에 추가해 NgModule 기반 컴포넌트에서 사용할 수도 있습니다.

angular
@Directive({
  selector: '[appHighlight]',
  standalone: true,
})
export class HighlightDirective { ... }

@Pipe({
  name: 'truncate',
  standalone: true,
})
export class TruncatePipe implements PipeTransform { ... }

// use directly in a standalone component's imports
@Component({
  imports: [HighlightDirective, TruncatePipe],
  template: `<p appHighlight>{{ text | truncate:10 }}</p>`,
})

NgModule에서 마이그레이션

schematic이 마이그레이션을 자동화합니다: 모든 declarations를 standalone으로 만들고, NgModule의 imports를 각 컴포넌트의 imports 배열로 옮기며, 쓸모없어진 모듈을 제거합니다. 부분적으로 실행할 수 있으니 점진적으로 진행하세요. 마이그레이션 후 AppRoutingModule, AppModule을 삭제하고 bootstrapApplication을 사용할 수 있습니다. 결과는 더 가볍고 tree-shakeable한 앱입니다.

angular
# automatic migration (v15.2+)
ng generate @angular/core:standalone

# options:
# 1. Convert all components/directives/pipes to standalone
# 2. Remove unnecessary NgModule classes
# 3. Bootstrap the app using bootstrapApplication

// before: declared in a module
@NgModule({
  declarations: [OldComponent],
  imports: [CommonModule],
  exports: [OldComponent],
})
export class OldModule {}

// after: standalone component
@Component({
  standalone: true,
  imports: [CommonModule],
  // ...
})
export class OldComponent {}

standalone 프로바이더 주입

standalone 앱은 AppModule 대신 app.config.ts에서 프로바이더를 설정합니다. APP_INITIALIZER는 부트스트랩 전에 설정 작업을 실행합니다. 컴포넌트 수준 프로바이더는 해당 컴포넌트 서브트리로 스코프가 한정됩니다. 서비스는 여전히 providedIn: 'root'가 선호됩니다 — tree-shakeable하기 때문입니다. providers 배열은 서비스가 아닌 값(토큰, 설정, 목)에 사용하세요.

angular
// app.config.ts — global providers
export const appConfig: ApplicationConfig = {
  providers: [
    { provide: API_URL, useValue: 'https://api.example.com' },
    { provide: ErrorHandler, useClass: GlobalErrorHandler },
    { provide: APP_INITIALIZER, multi: true, useFactory: () => initApp },
  ],
};

// component-level providers (scoped to this component and children)
@Component({
  providers: [
    { provide: UserService, useClass: MockUserService },
  ],
})
export class AdminComponent {}

// tree-shakable service
@Injectable({ providedIn: 'root' })  // preferred over providers array
export class AuthService {}
19

시그널(Signals)

시그널 만들기

signal()은 반응형 값을 만듭니다. 함수 호출로 읽습니다: count(). set()(교체) 또는 update()(이전 값에서 계산)로 업데이트합니다. 시그널은 동기적이어서 단순 상태에 Observable의 오버헤드를 피합니다. 템플릿에서는 ()로 호출할 수 있고 — v17.2+에서는 일부 컨텍스트에서 자동 언랩됩니다. 시그널은 OnPush 변경 감지와 통합됩니다.

angular
import { signal, computed, effect } from '@angular/core';

export class CounterComponent {
  // writable signal with initial value
  count = signal(0);
  user = signal<User | null>(null);

  // reading: call the signal as a function
  current = this.count();    // 0

  // writing
  increment() { this.count.update(v => v + 1); }
  setFive() { this.count.set(5); }

  // in templates, signals are called automatically in v17.2+
  // {{ count }} or {{ count() }} both work in templates
}

Computed 시그널

computed()는 의존성을 자동 추적하고 값을 캐싱하는 파생 읽기 전용 시그널을 만듭니다. 의존성이 바뀌고 다시 읽힐 때만 재계산됩니다 — 지연 평가입니다. computed 시그널은 다른 computed 시그널에 의존해 그래프를 이룰 수 있습니다. 메서드와 달리 결과를 캐싱합니다. 이것은 RxJS combineLatest의 많은 용도를 대체합니다.

angular
export class CartComponent {
  items = signal<Item[]>([]);
  taxRate = signal(0.08);

  // derived state — recomputes only when items or taxRate change
  subtotal = computed(() =>
    this.items().reduce((sum, i) => sum + i.price * i.qty, 0)
  );
  tax = computed(() => Math.round(this.subtotal() * this.taxRate() * 100) / 100);
  total = computed(() => this.subtotal() + this.tax());

  // computed signals are readonly and cached
  // they recompute lazily only when read AND a dependency changed
}

Effect (부수 효과)

effect()는 시그널 의존성이 바뀔 때 부수 효과를 실행합니다. 로깅, localStorage 동기화, 데이터 가져오기, DOM 조작에 사용하세요. effect는 변경 감지 후에 실행됩니다. 같은 effect 안에서 읽는 시그널에 쓰지 마세요 — 무한 루프가 됩니다. onCleanup은 다음 실행 전 정리 로직을 등록합니다. effect는 주입 컨텍스트에서 생성해야 합니다.

angular
export class SearchComponent {
  query = signal('');
  results = signal<Result[]>([]);

  constructor() {
    // effect runs when its signal dependencies change
    effect(() => {
      const q = this.query();
      // ⚠️ avoid setting signals read in this effect (causes loops)
      this.search(q).then(r => this.results.set(r));
    });
  }

  // effect with cleanup
  private log = effect((onCleanup) => {
    const id = setInterval(() => console.log(this.count()), 1000);
    onCleanup(() => clearInterval(id));
  });
}

템플릿의 시그널 (OnPush)

시그널은 OnPush와 매끄럽게 통합됩니다 — Angular가 어떤 뷰가 시그널에 의존하는지 정확히 알아 변경 시 해당 뷰만 검사 대상으로 표시합니다. 수동 markForCheck()가 필요 없습니다. 템플릿에서는 ()로 시그널을 호출해 읽습니다. OnPush + 시그널이 가장 효율적인 변경 감지 구성이며, zone.js를 완전히 제거할 수 있게 해 줍니다(zoneless 모드).

angular
@Component({
  selector: 'app-todo',
  // signals work great with OnPush — automatic efficiency
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `
    <input (input)="text.set($any($event.target).value)" />
    <p>You typed: {{ text() }}</p>
    <p>Length: {{ length() }}</p>
    <button (click)="clear()">Clear</button>
  `,
})
export class TodoComponent {
  text = signal('');
  length = computed(() => this.text().length);
  clear() { this.text.set(''); }
}

시그널 Input과 쿼리

input()/input.required()는 읽기 전용 시그널 input을 만듭니다. output()은 타입이 지정된 output을 만듭니다. model()은 양방향 바인딩 가능한 시그널 input을 만듭니다(자동 생성된 xChange output 포함). viewChild()/contentChild()는 뷰 초기화 후 해결되는 시그널을 반환합니다 — ()로 호출해 읽으세요. 이 모던 API들은 @Input/@Output/@ViewChild 데코레이터를 반응형 시그널로 대체합니다.

angular
import { input, output, viewChild, contentChild, model } from '@angular/core';

export class EditComponent {
  // signal input (readonly, v17.1+)
  id = input<number>(0);
  requiredName = input.required<string>();

  // signal output (v17.3+)
  saved = output<User>();

  // two-way signal (v17.2+)
  value = model<number>(0);   // creates input + output named valueChange

  // signal queries
  inputEl = viewChild<ElementRef>('input');      // in own template
  header = contentChild<TemplateRef>('header');  // projected content

  focus() { this.inputEl()?.nativeElement.focus(); }
}

시그널과 RxJS 상호 운용

toSignal은 Observable을 시그널로 변환합니다(한 번 구독, destroy 시 해제). toObservable은 그 반대입니다. 시그널(동기 상태용)과 RxJS(디바운스 검색 같은 복잡한 비동기 흐름용)를 섞을 때 상호 운용을 사용하세요. takeUntilDestroyed는 DestroyRef로 자동 구독 해제합니다. initialValue는 첫 방출 전 undefined 읽기를 막습니다. 주입 컨텍스트가 필요합니다.

angular
import { toSignal, toObservable, takeUntilDestroyed } from '@angular/core/rxjs-interop';

export class SearchComponent {
  private http = inject(HttpClient);

  // Observable → Signal (one-way)
  results = toSignal(this.http.get<Result[]>('/api/results'), {
    initialValue: [] as Result[],
  });

  // Signal → Observable (for RxJS operators)
  private query$ = toObservable(this.query);

  // combine the best of both worlds
  filtered = toSignal(
    this.query$.pipe(
      debounceTime(300),
      switchMap(q => this.http.get(`/api/search?q=${q}`)),
      takeUntilDestroyed(),
    ),
    { initialValue: [] as Result[] },
  );
}
20

NgModule과 아키텍처

NgModule 구조

NgModule은 앱을 응집력 있는 블록으로 조직화합니다. declarations는 모듈이 소유한 것들입니다. imports는 다른 모듈의 export를 가져옵니다. exports는 declarations를 임포터에게 노출합니다. bootstrap은 루트 모듈만 설정합니다. 모던 Angular는 standalone 컴포넌트(NgModule 없음)를 선호하지만 NgModule 앱도 여전히 존재합니다. 둘 다 이해하세요 — 구형 코드베이스와 일부 라이브러리는 모듈을 사용합니다.

angular
@NgModule({
  declarations: [                  // components, directives, pipes owned by this module
    AppComponent,
    UserListComponent,
    HighlightDirective,
    TruncatePipe,
  ],
  imports: [                       // other modules whose exports this module needs
    BrowserModule,
    FormsModule,
    HttpClientModule,
    AppRoutingModule,
  ],
  exports: [                       // what's visible to modules that import this module
    UserListComponent,
    TruncatePipe,
  ],
  providers: [],                   // services (use providedIn: 'root' instead)
  bootstrap: [AppComponent],       // only in the root module
})
export class AppModule {}

기능 모듈과 공유 모듈

SharedModule은 기능 전반에서 재사용할 공통 UI 컴포넌트/디렉티브/파이프를 묶습니다 — 임포터가 따로 할 필요 없게 CommonModule과 FormsModule을 re-export하세요. 기능 모듈은 기능 영역을 캡슐화하며, forChild()는 같은 모듈이 임포트마다 다르게 설정되게 합니다(예: 라우팅). standalone 앱에서는 공유 모듈보다 개별 standalone 컴포넌트를 선호하세요.

angular
// shared.module.ts — reusable UI bits
@NgModule({
  imports: [CommonModule, FormsModule],
  declarations: [ButtonComponent, CardComponent, HighlightDirective],
  exports: [ButtonComponent, CardComponent, HighlightDirective, FormsModule],
})
export class SharedModule {}

// feature module (lazy-loaded)
@NgModule({
  declarations: [AdminComponent, AdminUsersComponent],
  imports: [CommonModule, RouterModule, SharedModule],
  exports: [AdminComponent],
})
export class AdminModule {
  static forChild(): ModuleWithProviders<AdminModule> {
    return { ngModule: AdminModule, providers: [AdminService] };
  }
}

Core 모듈과 싱글턴 서비스

CoreModule은 앱 전역 싱글턴(서비스, 인터셉터, 오류 핸들러)을 담고 AppModule에서 한 번만 임포트됩니다. 생성자 가드는 실수로 재임포트되는 것을 막습니다(재임포트되면 서비스 인스턴스가 중복됩니다). standalone 앱에서는 이 프로바이더들이 app.config.ts로 이동합니다. CoreModule 패턴은 레거시지만 v14 이전 코드베이스에서 만나게 됩니다.

angular
// core.module.ts — app-wide singletons, imported once in AppModule
@NgModule({
  providers: [
    AuthService,
    { provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true },
    { provide: ErrorHandler, useClass: GlobalErrorHandler },
  ],
})
export class CoreModule {
  // guard against importing twice
  constructor(@Optional() @SkipSelf() parent?: CoreModule) {
    if (parent) throw new Error('CoreModule already loaded');
  }
}

forRoot vs forChild 패턴

forRoot는 루트 인스턴스를 설정하고(AppModule에서 한 번 호출), forChild는 자식 라우트를 등록합니다(기능 모듈에서 호출). 이 패턴은 RouterModule과 설정이 필요한 라이브러리 모듈이 사용합니다. 모던 Angular는 app.config.ts의 provideX() 함수로 이를 대체합니다. 서드파티 라이브러리에서 여전히 나타나므로 통합을 위해 이해해 두세요.

angular
// classic RouterModule pattern
@NgModule({ imports: [CommonModule], exports: [RouterModule] })
export class RouterModule {
  static forRoot(routes: Routes): ModuleWithProviders<RouterModule> {
    return {
      ngModule: RouterModule,
      providers: [provideRouter(routes)],
    };
  }
  static forChild(routes: Routes): ModuleWithProviders<RouterModule> {
    return { ngModule: RouterModule, providers: [provideRoutes(routes)] };
  }
}

// AppModule imports: RouterModule.forRoot(ROUTES)
// FeatureModule imports: RouterModule.forChild(FEATURE_ROUTES)

// modern equivalent: provideRouter(routes) in app.config.ts

Entry 컴포넌트와 동적 생성

entryComponents(지원 중단)는 동적으로 생성되는 컴포넌트(다이얼로그, 모달)를 나열했습니다. 모던 Angular는 ViewContainerRef.createComponent()나 NgComponentOutlet을 사용합니다 — 등록이 필요 없습니다. standalone 컴포넌트와도 매끄럽게 동작합니다. createComponent는 .instance와 .destroy()를 가진 ComponentRef를 반환합니다. 누수를 피하려면 destroy()를 호출해 정리하세요.

angular
// older API: entryComponents for dynamically created components
@NgModule({
  entryComponents: [DialogComponent, ModalComponent],
})
export class AppModule {}

// modern: ViewContainerRef.createComponent (no entryComponents needed)
export class DialogService {
  constructor(private vcr: ViewContainerRef) {}

  open() {
    const ref = this.vcr.createComponent(DialogComponent);
    ref.instance.title = 'Hello';
    ref.instance.close.subscribe(() => ref.destroy());
    return ref;
  }
}

// even simpler: NgComponentOutlet in template
<ng-container *ngComponentOutlet="dialogComponent; inputs: { title: 'Hi' }" />

Lazy 로드 모듈

lazy 로드 모듈은 내비게이션 시 로드되는 별도 JS 청크를 만듭니다. 번들러가 분할하려면 dynamic import() 문자열이 정적이어야 합니다. lazy 모듈은 자체 루트 인젝터를 가지므로 lazy 모듈에서 providedIn된 서비스는 앱 전체 싱글턴이 아닙니다. 모던 standalone 앱은 라우트 파일과 함께 loadComponent/loadChildren을 사용합니다 — 더 단순하고 세분화되어 있습니다.

angular
// classic lazy module (pre-standalone)
const routes: Routes = [
  {
    path: 'admin',
    loadChildren: () => import('./admin/admin.module').then(m => m.AdminModule),
  },
];

// admin-routing.module.ts
const routes: Routes = [
  { path: '', component: AdminComponent },
  { path: 'users', component: AdminUsersComponent },
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule],
})
export class AdminRoutingModule {}

// admin.module.ts
@NgModule({
  declarations: [AdminComponent, AdminUsersComponent],
  imports: [CommonModule, AdminRoutingModule],
})
export class AdminModule {}

Was this helpful?

Learning path

Learn from scratch

Learn this language from the ground up with structured lessons.