Angular 애플리케이션을 개발하면 여러 페이지를 보여주고, 각 페이지에 대한 경로를 설정해야 합니다. 이를 위해 Angular에서는 라우팅을 사용하여 페이지 간의 전환이나 새로고침 없이 특정 URL에 따라 다른 컴포넌트를 표시할 수 있습니다. Angular의 라우팅을 위해 RouterModule 모듈을 사용하고, RouterModule.forRoot 및 RouterModule.forChild를 통해 라우팅 구성을 정의할 수 있습니다.
라우팅 모듈 생성
일반적으로 라우팅 설정은 별도의 라우팅 모듈에서 관리됩니다. 새 라우팅 모듈을 생성하려면 다음과 같이 진행합니다:
ng generate module app-routing --flat --module=app
위 명령을 실행하면 app-routing.module.ts 파일이 생성됩니다. 이 파일에서 라우팅을 추가하고 애플리케이션 모듈에 등록할 수 있습니다.
라우팅 설정
app-routing.module.ts 파일에서 라우팅을 설정합니다. 아래의 코드는 간단한 라우팅 설정 예시입니다:
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './home.component';
import { AboutComponent } from './about.component';
const routes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'about', component: AboutComponent }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
위의 코드에서 RouterModule.forRoot를 통해 라우팅 구성을 정의하고, imports 배열에 등록합니다. 그리고 exports 배열에서 RouterModule를 내보내어 애플리케이션 모듈에서 사용할 수 있도록 합니다.
AppComponent에서 라우터 사용
app.component.html 파일에서 라우팅을 이용하여 컴포넌트를 표시할 수 있습니다. 아래의 코드는 라우팅을 추가한 예시입니다:
<nav>
<a routerLink="/">Home</a>
<a routerLink="/about">About</a>
</nav>
<router-outlet></router-outlet>
**
마무리
Angular의 모듈 라우팅을 통해 애플리케이션에서 다양한 페이지 간의 전환 및 컴포넌트 표시를 간단하게 구현할 수 있습니다. 라우팅을 통해 사용자 경험을 향상시키고, 애플리케이션의 유지보수를 용이하게 할 수 있습니다.
이러한 라우팅 설정을 통해 당신의 Angular 애플리케이션을 더욱 효과적으로 관리하고 발전시킬 수 있습니다.
참고 문헌:
- Angular 라우터 가이드: Angular 라우터
- Angular 공식 문서: Angular 공식 문서
그럼 방문해주셔서 감사합니다!