Learn Component Routing in Angular

To call or navigate to a component from another component in Angular, you typically use Angular's Router service for component routing. Here's how you can achieve this.

Define Routes in the Router Module

First, you need to set up your routes in your AppRoutingModule (or any routing module you've defined). Define the paths and the corresponding components.

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { ComponentA } from './component-a/component-a.component';
import { ComponentB } from './component-b/component-b.component';

const routes: Routes = [
  { path: 'component-a', component: ComponentA },
  { path: 'component-b', component: ComponentB },
  // Add more routes as needed
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

Use RouterLink in Templates

You can navigate to another component using the RouterLink directive in your template (HTML) of the first component.

<!-- component-a.component.html -->
<a [routerLink]="['/component-b']">Go to Component B</a>

Navigate Programmatically Using the Router

You can also navigate programmatically using the Angular Router in your component's TypeScript file.

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

@Component({
  selector: 'app-component-a',
  templateUrl: './component-a.component.html',
  styleUrls: ['./component-a.component.css']
})
export class ComponentA {

  constructor(private router: Router) { }

  goToComponentB() {
    this.router.navigate(['/component-b']);
  }
}

In HTML template

<!-- component-a.component.html -->
<button (click)="goToComponentB()">Go to Component B</button>

Outlet to Render Routed Components

Ensure you have a <router-outlet></router-outlet> in your main HTML template (e.g., app.component.html) where the routed components will be displayed.

<!-- app.component.html -->
<router-outlet></router-outlet>

Lazy Loading (Optional)

If you want to load a module lazily, define your route like this.

const routes: Routes = [
  {
    path: 'component-b',
    loadChildren: () => 
      import('./component-b/component-b.module')
        .then(m => m.ComponentBModule)
  }
];

Summary

  • RouterLink: For navigation within the template.
  • Router.navigate: For programmatic navigation within the component's TypeScript file.
  • Router Outlet: Acts as a placeholder in the template where routed components are displayed.

This setup allows you to call or navigate between components effectively in Angular.