mirror of
https://github.com/angular/skills.git
synced 2026-09-14 16:13:23 +08:00
2.1 KiB
2.1 KiB
Define Routes
Routes are objects that define which component should render for a specific URL path.
Basic Configuration
Define routes in a Routes array and provide them using provideRouter in your appConfig.
// app.routes.ts
export const routes: Routes = [
{path: '', component: HomePage},
{path: 'admin', component: AdminPage},
];
// app.config.ts
export const appConfig: ApplicationConfig = {
providers: [provideRouter(routes)],
};
URL Paths
- Static: Matches an exact string (e.g.,
'admin'). - Route Parameters: Dynamic segments prefixed with a colon (e.g.,
'user/:id'). - Wildcard: Matches any URL using
**. Useful for "Not Found" pages. Always place at the end of the array.
Matching Strategy
Angular uses a first-match wins strategy. Specific routes must come before less specific ones.
Redirects
Use redirectTo to point one path to another.
{ path: 'articles', redirectTo: '/blog' },
{ path: 'blog', component: Blog },
Conditional Redirects
Pass a function to redirectTo to apply logic when redirecting.
{
path: 'restaurant/:location/menu',
redirectTo: ({ params }) => {
const base = `/restaurant/${params['location']}/menu`;
const hour = new Date().getHours();
if (hour < 11) return `${base}/breakfast`;
if (hour < 17) return `${base}/lunch`;
return `${base}/dinner`;
},
},
Page Titles
Associate titles with routes for accessibility. Titles can be static or dynamic (via ResolveFn or a custom TitleStrategy).
{ path: 'home', component: Home, title: 'Home Page' }
Route Data and Providers
- Static Data: Attach metadata using the
dataproperty. - Route Providers: Scope dependencies to a specific route and its children using the
providersarray.
Nested (Child) Routes
Define sub-views using the children property. Parent components must include a <router-outlet />.
{
path: 'product/:id',
component: Product,
children: [
{ path: 'info', component: ProductInfo },
{ path: 'reviews', component: ProductReviews },
],
}