Router Configuration

Back

Loading concept...

🏠 Angular Router Configuration: Your App’s GPS System

Imagine your Angular app is a big building with many rooms. The Router is like a smart GPS that helps visitors find exactly the right room AND tells them what that room is called!


🌟 The Big Picture

When you visit a website, you see different pages. But how does Angular know:

  1. What page to show? (That’s regular routing)
  2. What to call the page in the browser tab? (That’s Route Title)
  3. How to customize ALL page titles at once? (That’s TitleStrategy)
  4. How to give the router special powers? (That’s Router Providers)

Let’s explore each one like we’re setting up the world’s coolest building!


📖 Route Title: Naming Your Rooms

What Is It?

Think of Route Title like the name tag on each door. When someone enters a room, they see the room’s name in the browser tab!

Simple Example

const routes: Routes = [
  {
    path: 'home',
    component: HomeComponent,
    title: 'Welcome Home'  // 👈 This shows in browser tab!
  },
  {
    path: 'about',
    component: AboutComponent,
    title: 'About Us'
  }
];

What happens?

  • User goes to /home → Browser tab says “Welcome Home”
  • User goes to /about → Browser tab says “About Us”

Why Is This Cool?

  • Users know which page they’re on
  • Better for bookmarks
  • Helps search engines understand your site
graph TD A["User clicks link"] --> B["Router loads page"] B --> C["Browser tab updates"] C --> D["Shows Route Title!"]

Dynamic Titles with Resolver

What if you want the title to change based on data? Use a Resolver!

// title.resolver.ts
export const dynamicTitle: ResolveFn<string> =
  (route) => {
    const id = route.paramMap.get('id');
    return `Product #${id}`;
  };

// routes
{
  path: 'product/:id',
  component: ProductComponent,
  title: dynamicTitle  // 👈 Function instead of string!
}

Now visiting /product/42 shows “Product #42” in the tab!


🎨 TitleStrategy: The Master Controller

What Is It?

TitleStrategy is like a manager who decides HOW all room names should look. Instead of going door-to-door, you set ONE rule for everyone!

Default Behavior

Angular has a default TitleStrategy that just uses whatever you put in title.

Creating Custom TitleStrategy

Want EVERY page to say “MyApp - [Page Name]”? Create your own strategy!

// custom-title.strategy.ts
@Injectable({ providedIn: 'root' })
export class CustomTitleStrategy
  extends TitleStrategy {

  constructor(private titleService: Title) {
    super();
  }

  override updateTitle(
    routerState: RouterStateSnapshot
  ): void {
    const title = this.buildTitle(routerState);
    if (title) {
      this.titleService.setTitle(
        `MyApp - ${title}`
      );
    } else {
      this.titleService.setTitle('MyApp');
    }
  }
}

Registering Your Strategy

// app.config.ts
export const appConfig: ApplicationConfig = {
  providers: [
    provideRouter(routes),
    {
      provide: TitleStrategy,
      useClass: CustomTitleStrategy
    }
  ]
};

The Result

Route Title Browser Tab Shows
'Home' MyApp - Home
'About Us' MyApp - About Us
(none) MyApp
graph TD A["Route has title"] --> B["TitleStrategy takes over"] B --> C["Adds &&#35;39;MyApp -&&#35;39; prefix"] C --> D["Sets final title in browser"]

🔧 Router Providers: Giving Router Superpowers

What Is It?

Router Providers are like special tools and gadgets you give to your router. They change how routing behaves!

The Main Function: provideRouter()

This is the basic toolkit every router needs:

// app.config.ts
import { provideRouter } from '@angular/router';

export const appConfig: ApplicationConfig = {
  providers: [
    provideRouter(routes)  // 👈 Basic router setup
  ]
};

Adding Features with Functions

Angular gives you feature functions to add powers:

import {
  provideRouter,
  withHashLocation,
  withInMemoryScrolling,
  withRouterConfig
} from '@angular/router';

export const appConfig: ApplicationConfig = {
  providers: [
    provideRouter(
      routes,
      withHashLocation(),  // Use # in URLs
      withInMemoryScrolling({
        scrollPositionRestoration: 'enabled'
      }),
      withRouterConfig({
        onSameUrlNavigation: 'reload'
      })
    )
  ]
};

Common Router Features

Feature Function What It Does
withHashLocation() URLs use # (like /#/home)
withInMemoryScrolling() Remembers scroll position
withRouterConfig() Advanced router settings
withDebugTracing() Shows routing in console
withPreloading() Loads pages before needed

Example: Enable Debug Mode

Want to see what the router is doing?

provideRouter(
  routes,
  withDebugTracing()  // 👈 Logs everything!
)

Now check your browser console to see every routing step!

graph TD A["provideRouter"] --> B["Basic Routing"] A --> C["+ withHashLocation"] A --> D["+ withInMemoryScrolling"] A --> E["+ withDebugTracing"] C --> F["Enhanced Router!"] D --> F E --> F

🎯 Putting It All Together

Here’s a complete example using ALL three concepts:

// routes.ts
export const routes: Routes = [
  {
    path: '',
    component: HomeComponent,
    title: 'Home'
  },
  {
    path: 'shop',
    component: ShopComponent,
    title: 'Shop'
  },
  {
    path: 'cart',
    component: CartComponent,
    title: 'Your Cart'
  }
];

// custom-title.strategy.ts
@Injectable({ providedIn: 'root' })
export class AppTitleStrategy
  extends TitleStrategy {

  constructor(private title: Title) {
    super();
  }

  updateTitle(state: RouterStateSnapshot) {
    const pageTitle = this.buildTitle(state);
    this.title.setTitle(
      pageTitle ? `🛒 ShopApp | ${pageTitle}` : '🛒 ShopApp'
    );
  }
}

// app.config.ts
export const appConfig: ApplicationConfig = {
  providers: [
    provideRouter(
      routes,
      withInMemoryScrolling({
        scrollPositionRestoration: 'enabled'
      })
    ),
    {
      provide: TitleStrategy,
      useClass: AppTitleStrategy
    }
  ]
};

Result:

  • / → Tab shows “🛒 ShopApp | Home”
  • /shop → Tab shows “🛒 ShopApp | Shop”
  • /cart → Tab shows “🛒 ShopApp | Your Cart”

🚀 Quick Recap

Concept What It Does Think Of It As…
Route Title Names individual pages Door name tags
TitleStrategy Controls ALL titles The manager
Router Providers Adds router features Superpowers toolkit

💡 Pro Tips

  1. Always add titles - It helps users and SEO!
  2. Use TitleStrategy for consistent branding
  3. Start simple with provideRouter(routes)
  4. Add features only when you need them

You’ve just learned how to name your Angular rooms, manage all names from one place, and give your router superpowers! Now your app’s GPS is fully configured! 🎉

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.