Angular Router의 활용

라우터 및 라우팅 파라미터 설정

Route를 활용하여 라우팅을 할 경로와 매칭하는 컴포넌트를 선언한다.

Example

export const routes: Routes = [
  { path: '', redirectTo: 'product-list', pathMatch: 'full' },
  { path: 'product-list', component: ProductList },
  { path: 'product-details/:id', component: ProductDetails }
];

여기서 :id는 해당 경로의 라우팅 할때의 파라미터 값이 들어간다.

특정 라우팅을 수행하는 링크 걸기

html태그에서 해당 라우팅으로 이동할 수 있도록 링크를 걸 수 있다.

Example - html 코드 내에서 라우팅 시키는 경우 {% raw %}

<a *ngFor="let product of products"
  [routerLink]="['/product-details', product.id]">
  {{ product.name }}
</a>

{% endraw %}

example - 컴포넌트 상에서 라우팅 시키는 경우

goToProductDetails(id) {
  this.router.navigate(['/product-details', id]);
}

참고자료

라우팅 이벤트를 감지하여 함수 실행시키기

라우팅이 일어날 때마다 해당 이벤트를 감지하여 함수를 실행시킨다.

Example

constructor(router:Router) {
  router.events.subscribe(event:Event => {
    if(event instanceof NavigationStart) {
    }
    // NavigationEnd
    // NavigationCancel
    // NavigationError
    // RoutesRecognized
  });
}

현 페이지의 라우터 전달값을 받기

this.route.params.subscribe(
  params=>{
    this.sectionIndex=params['pageIndex'];
  }
)