# 再現手法
1. 以下のような2つのクラスを作る
    - 説明に必要な部分しか書かない
    - app.module.ts
```typescript
const routes: Routes = [
  { path: '', component: AppComponent },
  { path: 'hoge', loadChildren: './hoge#HogeModule' }
];
@NgModule({
  declaration: [
    AppComponent
  ],
  imports: [
    RouteModule.forRoot(routes),
    HogeModule
  ]
})
export class AppModule { ... }
```
    - hoge.module.ts
```typescript
@NgModule({
  declarations: [
    HogeComponent
  ],
  imports: [
    RouteModule.forChild(routes),
  ]
})
export class HogeModule { ... }
```
1. `/` へアクセスする

# 発生する事象
- HogeComponent が表示されてしまう

# 期待される動作
- AppComponent が表示される

# なんでこんなこと起きるの?
- 調べたけど原因はよくわからなかった…
    - https://stackoverflow.com/questions/40816415/angular2-submodules-forchild-routes-overwrite-root-routes
- ただ、挙動的には親から import するモジュールで、 `RouterModule` を使っているとルーティングが上書きされる

# 期待される動作への修正方法
## 1. HogeComponent を分離する
- 親からインポートするためのモジュールと、ルーティングを含めたモジュールの2つに分離する
    - 前者を `HogeModule` のまま、後者を `HogeRoutingModule` で新規に作成する
    - `HogeModule` から `RouterModule` の import を消す
    - `HogeRoutingModule` には `RouterModule` と `HogeModule` のみ import する
    - `hoge.module.ts`
```typescript
@NgModule({
  declarations: [
    HogeComponent
  ],
  imports: [
    // RouterModule を抜く
  ]
})
export class HogeModule { ... }
```
    - `hoge-routing.module.ts`
```typescript
@NgModule({
  imports: [
    RouterModule.forChild(routes),
    HogeModule
  ]
})
```

## 2. 親側のルーティングを修正する
- loadChildren するものを `RouterModule` が含まれている `HogeRoutingModule` へ修正する
    - app.module.ts
```typescript
const routes: Routes = [
  { path: '', component: AppComponent },
  { path: 'hoge', loadChildren: './hoge#HogeRoutingModule' } // 修正
];
@NgModule({
  declaration: [
    AppComponent
  ],
  imports: [
    RouteModule.forRoot(routes),
    HogeModule
  ]
})
export class AppModule { ... }
```

---

## Page Navigation

- Canonical URL: https://tips.weseek.co.jp/Tips/Angular/RouterModule%20を%20import%20しているモジュールの注意点
- Permalink: https://tips.weseek.co.jp/5fb74655a1ba4200489a4a61
- Parent: [Angular](/65069da24603e7ff39a6b3d6.md)
- Children: 0 total
- Total descendants: 0
- Siblings: 4 total
  - [AOTコンパイル](/5fb74a31a1ba4200489a4b04.md)
  - [EventEmitterはSubscribeしちゃだめです](/5fb745b1a1ba4200489a4a4e.md)
  - [splitting chunk に関するメモ](/5fb74a94a1ba4200489a4b0f.md)
  - [コンポーネントのメソッドをブラウザの開発者コンソールから呼び出す](/5fb746c1a1ba4200489a4a76.md)
- Last updated: 2020-11-20T04:52:56.428Z by takuya
- Full page listing (all children regardless of count): https://tips.weseek.co.jp/_api/v3/page-listing/children?id=5fb74655a1ba4200489a4a61
