Angularルーター:子ルートの定義

提供:Dev Guides
移動先:案内検索

ルーター構成で子ルートを使用することで、Angularアプリであらゆる種類のルーティング階層を簡単に作成できます。

以下では、Angular2+アプリのルーティングについて説明します。


子ルートを定義するために必要なのは、親構成のchildrenキーの一部として追加のルート構成オブジェクトの配列を追加することだけです。 構成例は次のとおりです。

const routes: Routes = [
  { path: '', component: ParentComponent, children: [
    { path: 'red', component: ChildComponent },
    { path: 'blue', component: AnotherChildComponent }
  ] }
];

また、親コンポーネントのテンプレートにrouter-outletディレクティブを追加することを忘れないでください。

<router-outlet></router-outlet>

このような構成では、使用可能なルートは / / red / blue になります(例: http:// localhost:4200 / red [ X132X])



子ルートには、独自の子ルートを含めることもできます。

const routes: Routes = [
  { path: '', component: ParentComponent, children: [
    { path: 'red', component: ChildComponent, children: [
      { path: 'knock-knock', component: SubChildComponent, children: [
        { path: 'neo', component: SubSubChildComponent }
      ] },
    ] },
    { path: 'blue', component: AnotherChildComponent }
  ] }
];

そして今、あなたは / red / knock-knock / neoにナビゲートすることによってウサギの穴の終わりに行くことができるでしょう🐇

パスのないルート

すべてのルートへのパスが必ずしも必要ではありません。 たとえば、前の構成でこのバリエーションを取り上げましょう。

const routes: Routes = [
  { path: '', component: ParentComponent, children: [
    { path: '', component: ChildComponent, children: [
      { path: 'knock-knock', component: SubChildComponent, children: [
        { path: 'neo', component: SubSubChildComponent }
      ] },
    ] },
    { path: 'blue', component: AnotherChildComponent }
  ] }
];

ChildComponentコンポーネントを含むルートにパスがないことに注意してください。 これは、ユーザーが / knock-knock / neo に直接移動することを意味しますが、ChildComponentは引き続きインスタンス化され、その子は引き続きルーターアウトレットに挿入されます。

コンポーネントレスルート

コンポーネントを持たない親ルートを持つことも可能です。

const routes: Routes = [
  { path: '', component: ParentComponent, children: [
    { path: 'red', children: [
      { path: 'knock-knock', component: SubChildComponent, children: [
        { path: 'neo', component: SubSubChildComponent }
      ] },
    ] },
    { path: 'blue', component: AnotherChildComponent }
  ] }
];

この構成でも、ユーザーは / red / knock-knock / neo に移動できますが、SubChildComponentParentComponentのルーターアウトレットに挿入されます。代わりは。

これは、パスが、コンポーネントのチェーンの残りの部分または兄弟コンポーネントで使用できるようにしたいデータまたはパラメーターを提供する場合に役立ちます。 例を挙げて説明しましょう。

const routes: Routes = [
  { path: '', component: ParentComponent, children: [
    { path: ':choice', children: [
      { path: 'neo', component: ChildComponent },
      { path: 'trinity', component: AnotherChildComponent }
    ] }
  ] }
];

この構成では、ChildComponentAnotherChildComponentの両方がchoiceパラメーターにアクセスでき、両方の兄弟をラップするためだけに別のダミーコンポーネントを含める必要はありませんでした。 。