✅ Angular 사용해보기 - URL 경로와 컴포넌트 연결하기
🔸 app.module.ts에 라우팅 규칙 추가
- 상세페이지 컴포넌트 만들어주시구
- app.module.ts 파일에서 상품 상세정보에 해당하는 라우팅 규칙을 추가
- path는 products/:productId
- component는 ProductDetailsComponent를 지정
@NgModule({
imports: [
BrowserModule,
ReactiveFormsModule,
RouterModule.forRoot([
{ path: '', component: ProductListComponent },
{ path: 'products/:productId', component: ProductDetailsComponent },
])
],
...
🔸 routerLink 프로퍼티 추가하기
- product-list.component.html 파일에서,
- 상품이름 표시 a태그에 routerLink 프로퍼티 추가, product.id 지정
...
<a
[title]="product.name + ' details'"
[routerLink]="['/products', product.id]">
{{ product.name }}
</a>
...
✅ 상품 상세정보 표시하기
- ProductDetailsComponent는 개별 상품의 정보를 표시
- 그리고 Angular Router는 사전에 정의된 라우팅 규칙 중에서 현재 브라우저의 URL에 매칭되는 컴포넌트를 화면에 표시
🔸 ActivatedRoute, 상품 배열 import
- product-details.component.ts 파일에 @angular/router 패키지로 제공되는 ActivatedRoute와 ../products 파일로 준비된 products 배열을 import
...
import { ActivatedRoute } from '@angular/router';
import { Product, products } from '../products';
🔸 product 프로퍼티를 정의
export class ProductDetailsComponent implements OnInit {
product: Product | undefined;
/* ... */
}
🔸 ActivatedRoute
- 생성자 소괄호 안에 private route: ActivatedRoute를 추가해서,
- ActivatedRoute를 constructor() 안에 의존성으로 주입합니다.
export class ProductDetailsComponent implements OnInit {
product: Product | undefined;
constructor(private route: ActivatedRoute) { }
}
- ActivatedRoute는 Angular Router가 로드한 개별 컴포넌트에 대한 정보를 담고 있음
- 때문에 이 객체를 참조하면 해당 컴포넌트가 표시될 때 사용된 라우팅 규칙이나 라우팅 인자를 확인할 수 있음
- ActivatedRoute를 의존성으로 주입하면 컴포넌트에서 이 서비스를 사용할 준비는 끝!
🔸 route.snapshot.paramMap
- ngOnInit() 메서드 안에서 라우팅 인자로 전달된 productId를 참조하고,
- 이 값에 해당되는 상품을 products 배열 안에서 찾음
ngOnInit() {
// First get the product id from the current route.
const routeParams = this.route.snapshot.paramMap;
const productIdFromRoute = Number(routeParams.get('productId'));
// Find the product that correspond with the id provided in route.
this.product = products.find(product => product.id === productIdFromRoute);
}
- 라우팅 인자는 라우팅 규칙에 변수로 선언
- 라우팅 인자에 접근하기 위해 이 예제에서는 route.snapshot으로 ActivatedRouteSnapshot을 참조
- 이 클래스는 현재 활성화된 라우팅 규칙에 대한 정보를 담고 있음
- 그래서 URL을 참조하면 productId를 참조할 수 있음
- Angular는 productId 자리에 해당 상품의 정보를 표시
🔸 화면에 정보 보여주기
- 상품의 상세정보를 표시할 수 있도록 ProductDetailsComponent 템플릿을 수정
- *ngIf를 사용해 해당 상품이 존재할 때만
<div>
엘리먼트가 렌더링되면서 상품의 이름, 가격, 설명이 화면에 표시
<h2>Product Details</h2>
<div *ngIf="product">
<h3>{{ product.name }}</h3>
<h4>{{ product.price | currency }}</h4>
<p>{{ product.description }}</p>
</div>
<h4>{{ product.price | currency }}</h4>
코드를 보면,
- product.price는 숫자 타입이지만 금액 형식으로 표시하기 위해 currency 파이프를 사용했음
- 파이프는 HTML 템플릿에 표시되는 데이터의 형식을 조작할 때 사용