SPA에서 페이지이동은 컴포넌트를 숨기거나 컴포넌트를 보이게 하는 것이며 앵귤러 Router클래스가 뷰전환을 담당한다.
앵귤러는 어플리케이션의 라우팅규칙을 관리하는 AppRoutingModule ngModule을 사용한다.
기본 라우팅규칙
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router'; // 라우터 관련 심볼을 로드합니다.
const routes: Routes = [
{ path: 'first-component', component: FirstComponent },
{ path: 'second-component', component: SecondComponent },
];
<nav>
<ul>
<li><a routerLink="/first-component" routerLinkActive="active">First Component</a></li>
<li><a routerLink="/second-component" routerLinkActive="active">Second Component</a></li>
</ul>
</nav>
<!-- 라우팅된 화면은 <router-outlet> 위치에 표시됩니다. -->
<router-outlet></router-outlet>
router-outlet는 화면이 전환될때 보여질 컴포넌트가 표시될 위치를 지정하는 엘리먼트다.
라우팅 규칙으로 전달된 정보 참조하기
뷰가 전환될때 교체되는 컴포넌트사이에 데이터를 전달해야 하는 경우가 발생한다.
{ path:'first/:id', component:FirstComponent},
:id로 라우팅규칙을 정해놓으면 브라우저 url은 first/123으로 변경된다.
전환된 컴포넌트에서 123값을 얻기위해서
import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute, ParamMap } from '@angular/router';
@Component({
selector: 'app-first',
templateUrl: './first.component.html',
styleUrls: ['./first.component.css']
})
export class FirstComponent implements OnInit {
constructor(private route: ActivatedRoute) { }
ngOnInit(): void {
let val = this.route.snapshot.paramMap.get('id');
console.log(val);
}
}
라우팅 라이브러리를 로드하고 this.route.snapshot.paramMap.get('id');으로 값을 얻을 수 있다.
this.route.queryParams.subscribe(params => {
this.id = params['id'];
});
옵저버블객체로 받을 수 도 있다.
constructor(private route: ActivatedRoute) { }
ngOnInit(): void {
console.log(this.route.snapshot.data['title']);
}
받을 수 있다.
<hr>
**와일드카드(*) 라우팅 규칙 등록하기**
{ path: '**', component: PageNotFoundComponent },
<hr>
**중첩 라우팅 규칙**
라우팅규칙을 현재url의 하위로 설정해야 할 경우가 있을 수 있다.
http://localhost:4200/first/second
{ path:'first', component:FirstComponent, children:[
{ path:'second', component:SecondComponent},
{ path:'third', component:ThirdComponent},
]},
라우팅규칙을 위와같이 children으로 하면 된다.
<hr>
**리다이렉션 설정하기**
const routes: Routes = [
{ path: 'first-component', component: FirstComponent },
{ path: 'second-component', component: SecondComponent },
{ path: '', redirectTo: '/', pathMatch: 'full' },
{ path: '**', component: PageNotFoundComponent },
];
redirectTo로 첫페이지로 리다이렉트할 수 있다.
** 별표2개는 없는 페이지로 이동하려할때 특정 컴포넌트로 이동시킬수 있다.
<hr>
**상대주소 사용하기**
상대 주소로 이동하기
<div><a routerLink="first" routerLinkActive="active">first</a></div>
routerLink디렉티브로 전환될 라이팅규칙을 지정해야 한다.
routerLinkActive는 해당페이지일때 CSS클래스를 지정한다.
goto() {
this.router.navigate(['path']) // 경로 지정
}
이벤트발생시 navigate메소드로 지정된 라우팅규칙으로 전환시킨다.