Query Parameters / Angular
Angular에서 쿼리 파라미터(Query Parameters)는 URL을 통해 데이터를 전달하거나 특정 상태를 나타낼 때 유용하게 사용됩니다.
Query Parameters
쿼리 파라미터는 URL에서 ?key=value 형식으로 데이터를 전달하는 방식입니다.
다중 데이터를 전달할 때는 &로 구분합니다.
https://example.com/products?category=books&sort=price
- category: books
- sort: price
Angular에서는 이를 활용하여 페이지 상태, 검색 조건 등을 관리할 수 있습니다.
쿼리 파라미터 설정하기
1. Router를 통한 설정
Router의 navigate 메서드를 사용해 쿼리 파라미터를 설정할 수 있습니다.
import { Component } from '@angular/core';
import { Router } from '@angular/router';
@Component({
selector: 'app-product-list',
template: `<button (click)="filterByCategory('books')">Books</button>`
})
export class ProductListComponent {
constructor(private router: Router) {}
filterByCategory(category: string) {
this.router.navigate(['/products'], {
queryParams: { category }
});
}
}
위 코드는 버튼 클릭 시 https://example.com/products?category=books로 이동합니다.
2. queryParamsHandling 옵션
기존 쿼리 파라미터를 유지하거나 대체할 때 사용됩니다.
- merge: 기존 쿼리 파라미터 유지하며 새로운 값 추가.
- preserve: 기존 값을 유지.
this.router.navigate(['/products'], {
queryParams: { sort: 'price' },
queryParamsHandling: 'merge'
});
쿼리 파라미터 읽기
1. ActivatedRoute로 읽기
ActivatedRoute의 queryParams Observable을 구독하거나, snapshot으로 즉시 값을 가져올 수 있습니다.
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-product-list',
template: `<p>Selected Category: {{ category }}</p>`
})
export class ProductListComponent implements OnInit {
category: string | null = null;
constructor(private route: ActivatedRoute) {}
ngOnInit() {
// 1. Observable 방식
this.route.queryParams.subscribe(params => {
this.category = params['category'] || 'all';
});
// 2. Snapshot 방식
// this.category = this.route.snapshot.queryParams['category'] || 'all';
}
}
2. 쿼리 파라미터 변경 감지
Observable 방식을 사용하면 쿼리 파라미터 변경을 실시간으로 처리할 수 있습니다.
예제 : 필터링 기능
다음은 제품 목록에서 카테고리와 정렬 방식을 선택하는 UI입니다.
<div>
<label>
Category:
<select (change)="onCategoryChange($event)">
<option value="all">All</option>
<option value="books">Books</option>
<option value="electronics">Electronics</option>
</select>
</label>
<label>
Sort by:
<select (change)="onSortChange($event)">
<option value="name">Name</option>
<option value="price">Price</option>
</select>
</label>
</div>
TypeScript 코드
import { Component } from '@angular/core';
import { Router } from '@angular/router';
@Component({
selector: 'app-product-list',
templateUrl: './product-list.component.html'
})
export class ProductListComponent {
constructor(private router: Router) {}
onCategoryChange(event: Event) {
const category = (event.target as HTMLSelectElement).value;
this.router.navigate([], {
queryParams: { category },
queryParamsHandling: 'merge'
});
}
onSortChange(event: Event) {
const sort = (event.target as HTMLSelectElement).value;
this.router.navigate([], {
queryParams: { sort },
queryParamsHandling: 'merge'
});
}
}
이 코드는 쿼리 파라미터를 기반으로 필터와 정렬 상태를 관리합니다.
'개발 공부 > Angular' 카테고리의 다른 글
| ng-container / Angular (2) (0) | 2024.12.02 |
|---|---|
| ng-container / Angular (1) (1) | 2024.12.01 |
| Angular Router Guards (1) | 2024.11.24 |
| NgRx Component Store: 컴포넌트 중심의 상태 관리 (0) | 2024.11.23 |
| Angular Signals (2) (0) | 2024.11.21 |