본문 바로가기

IT/Angular

app-routing.module.ts 역할

✅ 역할 요약

app-routing.module.ts는
👉 URL 경로(path) 와
👉 해당 경로에 대응하는 컴포넌트(component) 를
매핑하는 라우팅 설정 파일입니다.

쉽게 말해:

“/home 주소에 들어가면 HomeComponent 보여줘~”
라는 걸 정의해두는 곳이에요.

 


✅ 구조 예시

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

import { HomeComponent } from './pages/home/home.component';
import { NoticeListComponent } from './pages/notice-list/notice-list.component';
import { NoticeDetailComponent } from './pages/notice-detail/notice-detail.component';

const routes: Routes = [
  { path: '', redirectTo: 'home', pathMatch: 'full' },
  { path: 'home', component: HomeComponent },
  { path: 'notices', component: NoticeListComponent },
  { path: 'notices/:id', component: NoticeDetailComponent }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule {}

✅ 핵심 개념 요약

요소설명
path 브라우저 URL 경로 (/home, /notices/:id 등)
component 해당 경로에 진입하면 보여줄 컴포넌트
RouterModule.forRoot(routes) 이 라우트들을 앱 전체에 등록
redirectTo 경로 리다이렉션 설정 (예: / → /home)
:id URL 파라미터 (예: /notices/123)

✅ 사용하는 이유?

  • Angular는 **SPA (Single Page Application)**이기 때문에,
    실제로 페이지가 전환되는 게 아니라
    URL만 바뀌고, 화면을 동적으로 바꿔주는 구조예요.
  • 그래서 라우팅 설정을 통해
    “어떤 주소일 때 어떤 컴포넌트를 보여줄지”를 지정해야 합니다.

✅ 관련 사용 예시

📌 템플릿에서 이동할 때

<a routerLink="/notices">알림 목록으로</a>

📌 컴포넌트에서 이동할 때

this.router.navigate(['/notices', notice.id]);

✅ 요약

질문답변
app-routing.module.ts는 무슨 역할 해? ✅ 경로(URL)와 화면(컴포넌트)을 연결하는 설정 파일이에요
왜 필요해? ✅ Angular는 SPA이기 때문에, URL에 따라 어떤 화면을 보여줄지 직접 설정해야 합니다
어떤 정보가 들어가? 경로(path), 컴포넌트(component), 리다이렉션, URL 파라미터 등

'IT > Angular' 카테고리의 다른 글

canActivate 에 대해서  (0) 2025.04.21