How to Navigate Programmatically in Angular

πŸ’‘ Concept Name

Programmatic Navigation in Angular allows you to redirect the user to different routes using the Router API without relying on link clicks.

πŸ“˜ Quick Intro

Instead of using <a [routerLink]>, Angular offers the Router service to change routes using navigate() or navigateByUrl(). This is useful in form submissions, conditionals, and guards.

🧠 Analogy / Short Story

Imagine a tour guide (Router) who leads tourists (users) to various spots (components) based on what they ask forβ€”no need to find the map and tap buttons, just say β€œTake me to Product 42,” and the guide leads you.

πŸ”§ Technical Explanation

  • πŸ“¦ Router Service: Inject Angular's Router in a component.
  • 🧭 navigate(): Uses an array of route segments to navigate.
  • πŸ“ navigateByUrl(): Accepts a full route string as a URL.
  • 🧾 Query Parameters: Can be passed as options object.
  • πŸ”™ Relative Navigation: Use ActivatedRoute for navigation relative to current path.

🎯 Purpose & Use Case

  • βœ… Redirect after form submission.
  • βœ… Conditional navigation based on logic (e.g., login status).
  • βœ… Auto-redirect in route guards or services.

πŸ’» Real Code Example


// Inside a component
import { Component } from '@angular/core';
import { Router } from '@angular/router';

@Component({ selector: 'app-example', template: '' })
export class ExampleComponent {
  constructor(private router: Router) { }

  goToProduct(id: number) {
    this.router.navigate(['/products', id]);
  }

  goWithQuery() {
    this.router.navigate(['/search'], { queryParams: { q: 'laptop' } });
  }
}

❓ Interview Q&A

Q1: What is the purpose of Router.navigate() in Angular?
A: It changes the current route programmatically using route segments.

Q2: When would you use navigateByUrl()?
A: When navigating to a URL string instead of segments.

Q3: How do you pass query parameters?
A: Use the queryParams option in the second argument.

Q4: What must be injected to use navigate() method?
A: The Router service.

Q5: Can you navigate relative to current route?
A: Yes, using ActivatedRoute with relativeTo.

πŸ“ MCQs

Q1. Which service is used for programmatic navigation?

  • Router
  • HttpClient
  • NgModule
  • Component

Q2. Which method accepts an array of route segments?

  • navigate()
  • navigateByUrl()
  • redirect()
  • goTo()

Q3. How do you pass query parameters?

  • URL only
  • data binding
  • Use queryParams option
  • RouterLink only

Q4. Which method takes a string URL?

  • navigate()
  • navigateByUrl()
  • routeTo()
  • load()

Q5. What does ActivatedRoute help with?

  • Form validation
  • Lazy loading
  • Relative routing
  • Data binding

Q6. Can navigation be triggered inside services?

  • No
  • Only in modules
  • Yes
  • Only in lifecycle hooks

Q7. When is programmatic navigation preferred?

  • For styles
  • Debugging
  • On form submit or auth check
  • Static routing

Q8. Which property enables navigation to /products?id=5?

  • param
  • routeOptions
  • queryParams
  • navData

Q9. What Angular type helps with current route info?

  • RouteInfo
  • NavigationState
  • ActivatedRoute
  • PathService

Q10. What is the output of router.navigate(['/about'])?

  • 404 error
  • Navigates to /home
  • Does nothing
  • Navigates to /about

πŸ’‘ Bonus Insight

Always prefer programmatic navigation when you need logic-based routing (like redirecting after login or processing API results). Also, remember to unsubscribe from route observables to avoid memory leaks.

πŸ“„ PDF Download

Need a handy summary for your notes? Download this topic as a PDF!

πŸ’¬ Feedback
πŸš€ Start Learning
Share:

Tags: