시작하기
CLI 설정과 프로젝트 생성
Angular CLI는 개발의 기본 도구입니다. ng new는 라우팅과 스타일이 미리 설정된 완전한 프로젝트를 스캐폴딩해 줍니다. 일관된 파일 생성을 위해 ng generate(ng g)를 사용하세요. 빌드, 테스트, 배포도 CLI가 처리합니다.
# 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을 바꿔 쓸 수 있습니다.
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를 실행합니다.
# 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로 만든 가드는 클래스 대신 함수를 반환합니다.
# 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가 포함됩니다. 하나의 워크스페이스에 여러 프로젝트(앱 + 라이브러리)를 함께 둘 수 있습니다.
{
"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 객체를 원하는 곳에 주입하면 하드코딩 없이 환경별 값을 사용할 수 있습니다. 실제 시크릿을 소스 관리에 커밋하지 마세요.
// 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;
}컴포넌트 기본
기본 컴포넌트
컴포넌트는 @Component 데코레이터가 붙은 TypeScript 클래스입니다. selector는 템플릿에서 사용할 커스텀 HTML 태그입니다. templateUrl/styleUrls는 외부 파일을 가리키고, 인라인으로 쓰려면 template/styles를 사용합니다. @Input은 부모가 바인딩할 수 있는 속성을 표시합니다. 컴포넌트는 하나의 책임에 집중하도록 유지하세요.
// 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줄을 넘어가면 외부 파일로 분리하는 것이 좋습니다.
@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에서 직접 부트스트랩합니다.
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를 사용하세요.
@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의 미래입니다.
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를 유지하세요.
@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)템플릿 문법
텍스트 보간(Interpolation)
이중 중괄호 {{ }}는 표현식을 HTML 이스케이프된 텍스트로 렌더링합니다. 산술, 삼항 연산자, 메서드 호출, 프로퍼티 접근 등 대부분의 JS 표현식을 쓸 수 있습니다. new, typeof, 대입 연산자는 사용할 수 없습니다. 파이프(|)로 출력을 변환합니다. 보간은 변경 감지 사이클마다 다시 평가됩니다.
<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에 바인딩하지 마세요.
<!-- 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 같은 이벤트 수식어로 이벤트를 걸러내거나 변형할 수 있습니다. 괄호 안의 대상이 핸들러를 트리거합니다.
<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가 암묵적 컨텍스트 변수로 제공됩니다.
<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() 시그널 함수가 이를 단순화합니다.
<!-- [()] = "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일 수 있는 배열에는 ?? []를 폴백으로 쓰세요.
<!-- 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) { ... }디렉티브
@if / @else (새 제어 흐름)
새로운 @if/@else if/@else 블록 문법은 *ngIf를 대체합니다. CommonModule이나 NgIf를 임포트할 필요가 없고, 별표(*)도 없으며, ngIf의 ng-template 우회법과 달리 @else가 기본 동작합니다. 새 코드에서 권장되는 문법입니다. v17에 도입된 내장 제어 흐름의 일부로 v18에서 안정화되었습니다.
@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하는 것이 중요합니다.
<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]가 더 가볍고 임포트도 필요 없습니다.
<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 이상에서 사용 가능한 내장 제어 흐름입니다.
@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를 선호합니다.
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 블록이 대부분의 커스텀 구조 디렉티브를 대체하지만, 고급 사례에서는 이 패턴이 여전히 유용합니다.
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> -->파이프(Pipes)
내장 파이프
파이프는 템플릿에서 표시되는 값을 변환합니다. 자주 쓰는 내장 파이프: date, number, currency, percent, uppercase, lowercase, titlecase, slice, json, async. 파이프는 기본적으로 pure이며 입력 참조가 바뀔 때만 다시 계산됩니다. 포맷 문자열은 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 파이프를 피하고 컴포넌트에서 계산하세요.
<!-- 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 파이프(기본값)는 입력 참조가 바뀔 때만 다시 실행되므로, 업데이트를 트리거하려면 새 참조를 전달해야 합니다.
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와도 통합됩니다.
@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 파이프를 사용하는 것이 성능상 좋습니다.
// 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로 폴백합니다.
// 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 -->서비스와 의존성 주입
기본 서비스
providedIn: 'root'는 모듈 등록 없이 앱 전역에서 사용 가능한 싱글턴을 만듭니다. 서비스는 tree-shakeable해서 사용하지 않으면 제거됩니다. 생성자 주입 대신 inject() 함수(v14+)를 쓰면 코드가 더 깔끔하고 테스트도 쉬워집니다. 서비스는 공유 상태와 비즈니스 로직을 담당하고, 컴포넌트는 프레젠테이션에 집중합니다.
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()가 더 깔끔합니다.
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은 문자열이나 설정 객체 같은 비클래스 값에 사용합니다.
@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'은 드물며 멀티 앱 구성에 사용됩니다.
// 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과 조합하면 배열에 타입을 부여할 수 있습니다.
// 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()도 옵션 객체에 플래그를 받아 동일하게 동작합니다.
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라우팅
라우트 설정
라우트는 URL 경로를 컴포넌트에 매핑합니다. loadComponent/loadChildren은 lazy loading을 활성화합니다(초기 번들 축소). :id는 라우트 파라미터입니다. 와일드카드 '**'는 매칭되지 않는 URL을 잡으며 마지막에 배치합니다. provideRouter는 standalone 앱에서 라우터를 설정합니다. 브라우저 탭 이름용 title을 지정하세요 — 문자열이나 ResolveFn이 될 수 있습니다.
// 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으로 보조 라우트(예: 메인 뷰 옆의 모달)를 만들 수 있습니다.
<!-- 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 파이프를 쓰세요.
// 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이 필요합니다.
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()의 문자열이 정적 경로여야 합니다. 내비게이션 뒤에 숨은 기능 영역에 사용하세요.
// 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로 읽을 수 있습니다.
// 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
});폼(Forms)
템플릿 기반 폼
템플릿 기반 폼은 ngModel과 템플릿 참조를 사용하며 FormsModule이 필요합니다. 폼의 상태(유효성, touched, dirty)는 ngForm과 ngModel 디렉티브로 추적됩니다. 단순한 폼에 적합합니다. 유효성 검사는 템플릿에서 선언합니다(required, minlength, pattern). #e='ngModel' 같은 템플릿 참조로 컨트롤 상태에 접근합니다.
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이 되지 않게 합니다. 복잡한 폼에 선호됩니다.
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 타입 검사를 제공합니다.
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')로 특정 오류를 검사합니다.
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)를 적용하세요.
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 }를 사용하세요.
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(); }
}HttpClient
설정과 기본 GET
provideHttpClient()는 클라이언트를 앱 전역에 등록합니다. HttpClient 메서드는 cold Observable을 반환하므로 구독해야 실행됩니다(템플릿에서는 async 파이프, 서비스에서는 subscribe 사용). 응답은 제네릭으로 타입을 지정합니다. 오류는 중앙에서 또는 호출별로 반드시 처리하세요. withFetch()(v18)는 모던한 fetch 기반 백엔드로 전환합니다.
// 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()을 고려하세요.
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를 함께 쓰면 파일 업로드/다운로드의 진행 이벤트를 스트리밍합니다.
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 연산자를 여기에 적용합니다.
// 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 콜백으로 구독하세요.
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 토큰 처리를 추가합니다.
// 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' }))Observable과 RxJS
기본 Observable
Observable은 지연(lazy) 동작합니다 — 구독해야 생산자가 실행됩니다. 값을 0개 이상 방출한 뒤 complete하거나 error합니다. subscribe 콜백은 next, error, complete를 받습니다. 오래 살아있는 구독은 반드시 해제하세요(또는 async 파이프 / takeUntilDestroyed 사용). of()는 값을 동기적으로 방출하고, from()은 배열이나 프로미스를 평탄화합니다.
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 연산자는 왼쪽에서 오른쪽으로 실행됩니다.
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만 택하고 나머지는 무시합니다.
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개 값을 버퍼링해 새 구독자에게 제공합니다(이벤트 리플레이에 사용).
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를 명시적으로 전달해야 합니다.
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은 무시합니다(중복 제출 방지). 잘못 고르면 경쟁 상태가 생기므로, 유스케이스의 취소 의미에 맞는 연산자를 선택하세요.
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)생명주기 훅
훅 실행 순서 개요
훅은 엄격한 순서로 실행됩니다. ngOnChanges는 @Input 변경 시(그리고 처음에) 실행됩니다. ngOnInit은 첫 ngOnChanges 후 한 번 실행됩니다. ngDoCheck는 모든 변경 감지 사이클에 실행됩니다. After* 훅은 콘텐츠/뷰가 DOM 조회 준비가 되었음을 알립니다. ngOnDestroy는 정리 지점입니다 — 구독 해제, 리소스 해제, 타이머 취소.
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에 작성하세요.
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를 사용하세요.
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* 훅에서만 안전하게 사용할 수 있습니다.
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를 사용하면 참조가 바뀌지 않는 배열/객체의 변형도 감지할 수 있습니다. 내부 변형 추적의 탈출구 역할을 합니다. 자주 실행되므로 무거운 로직은 피하세요 — 성능 문제를 일으킬 수 있습니다.
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는 자체 템플릿 엘리먼트를 조회합니다.
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
}콘텐츠 투영
기본 ng-content
<ng-content>는 부모가 제공한 콘텐츠가 투영되는 자리 표시자입니다. Angular의 <slot>이라고 생각하세요. select 없이는 모든 투영 콘텐츠가 여기에 들어갑니다. 투영된 콘텐츠는 부모 컨텍스트에서 컴파일됩니다 — {{ }} 같은 바인딩은 CardComponent가 아닌 부모 컴포넌트를 기준으로 해석됩니다.
// 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에서의 위치만 바뀝니다.
@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를 원하는 위 치에 렌더링합니다 — 탭, 아코디언, 조건부 슬롯에 유용합니다. 이 패턴은 콘텐츠 선언을 렌더링 위치/시점으로부터 분리합니다.
@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 등 특정 타입을 조회할 수 있습니다.
@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이 반복 변수를 전달하는 방식이 바로 이것입니다. 컴포넌트가 반복 로직을 제어하면서 부모가 커스터마이즈할 수 있는 재사용 가능한 목록/그리드/아이템 템플릿에 이 패턴을 사용하세요.
@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로 들어가고, 폴백이 없으면 버려집니다. 셀렉터는 투영된 엘리먼트 자신의 어트리뷰트에 매칭되며, 내부 구조에는 매칭되지 않습니다.
@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>라우트 가드
CanActivate (함수형)
함수형 가드(v14.2+)는 true/false/UrlTree 또는 이들의 Observable/Promise를 반환합니다. UrlTree를 반환하면 해당 라우트로 리다이렉트됩니다. 가드는 주입 컨텍스트에서 실행되므로 inject()를 쓸 수 있습니다. CanActivate는 라우트로의 내비게이션을 막습니다. canActivate 배열에 라우트별로 등록하며, 해당 라우트로 내비게이션할 때마다 실행됩니다.